Python Growth Notes-Basics (ii) Basic Python syntax

Source: Internet
Author: User
Tags arithmetic operators mathematical functions

One of the design goals of Python is to make the code highly readable. It is designed to use punctuation and English words often used in other languages to make the code look neat and tidy. Unlike other static languages such as C and Pascal, it does not have to be repeated to write declarative statements, nor does it often have special circumstances and surprises like their syntax.python indentPython developers intentionally make it impossible for a program that violates indentation rules to compile, forcing programmers to develop good programming habits. And the Python language uses indentation to represent the start and exit (Off-side rules) of a statement block, rather than using curly braces or some kind of keyword. Increasing the indentation represents the beginning of the statement block, and decreasing the indentation indicates the exit of the statement block. Indentation becomes part of the syntax. For example, if statement:?
1234 ifage<21: print("你不能买酒。") print("不过你能买口香糖。")print("这句话处於if语句块的外面。")
Note: The above example is Python version 3.0 code according to THE PEP rules, you must use 4 SpacesTo represent each level of indentation (it is unclear how the 4 spaces are defined, the number of spaces can be customized in actual writing, but the number of spaces per level of indentation is equal). Using the tab character and the other number of spaces can be compiled through, but not in accordance with the encoding specification. Support for tab characters and other numbers of spaces is just for compatibility with very old Python programs and some problematic editing programs.Python control StatementsIf statement, run the statement block when the condition is set. Often used in conjunction with else, elif (equivalent to else if). For statement, which iterates through the iterators, such as lists, strings, dictionaries, and collections, and sequentially processes each element in the iterator. While statement that loops through the statement block when the condition is true. Try statement. Use with except,finally to handle exceptions that occur during program operation. Class statement. Used to define the type. def statement. The method used to define functions and types. Pass statement. Indicates that this line is empty and does not run any operations. Assert statement. The test run condition is satisfied when used in the program debugging phase. With statement. Python2.6 The syntax that is defined later, running a block of statements in a scene. For example, the statement block is encrypted before it is run and then decrypted after the statement block runs out. Yield statement. Used within an iterator function to return an element. Since Python version 2.5. This statement becomes an operator. The Raise statement. Make a mistake. Import statement. Import a module or package. From import statement. Import a module from a package or import an object from a module. Import as statement. Assigns the imported object to a variable. In statement. Determines whether an object is in a string/list/tuple.python ExpressionsPython's expressions are written in a similar style to C + +. Only in some of the wording of the differences. The main arithmetic operators are similar to C + +. +,-, *,/,//, * *, ~,% respectively means addition or taking positive, subtraction or negative, multiplication, division, divisible, exponentiation, take-up, modulo. >> << represents right and left shifts. &, |, ^ denotes binary and, OR, XOR operations. <, = =,! =, <=, >= the values used to compare two expressions, respectively, are greater than, less than, equal to, not equal to, less than equals, greater than or equal to. Inside these operators, ~, |, ^, &, <<, >> must be applied to integers. Python uses and, or, not to represent logical operations. Is, are not used to compare whether two variables are the same object. In, no in is used to determine whether an object belongs to another object. Python supports list comprehension, such as calculating the sum of squares of 0-9 and:>>> sum (x * x for x in range) 285Python uses lambda to represent an anonymous function. An anonymous function body can only be an expression. For example:>>> Add=lambda x, y:x + y>>> Add (3,2) 5Python uses y if cond else x to represent conditional expressions. This means that when cond is true, the value of the expression is Y, otherwise the value of the expression is x. Equivalent to cond?y:x in C + + and Java. There are two types of Python (list) and tuple (tuple). The list is written in [All-in-one], and the tuple's notation is (a). You can change the elements in the list without changing the tuple. In some cases, the parentheses of a tuple can be omitted. Tuple has special handling for assignment statements. Therefore, can be assigned to multiple variables at the same time, such as:>>> X, y=1,2# also assigns to X, Y, the final result: X=1, y=2 Specifically, you can use the following form to exchange the value of two variables:>>> x, y=y, x #最终结果: y= 1, X=2python uses ' (single quotation marks) and "(double quotation marks) to represent the string. Unlike languages such as Perl, the Unix shell language, or Ruby, groovy, the two symbols work the same way. In general, if double quotation marks appear in a string, a single quotation mark is used to represent the string;It uses double quotation marks. If none of them appear, choose according to your preferences. The \ (backslash) that appears in the string is interpreted as a special character, such as \ n to represent a line break. The expression pre-plus r indicates that Python does not interpret \ As it appears in the string. This notation is commonly used to write regular expressions or Windows file paths. Python supports list slices, which can be part of a complete list. The types of support cutting operations are str, bytes, list, tuple and so on. Its syntax is ... [Left:right] or ... [Left:right:stride]. Assuming that the value of the nums variable is [1, 3, 5, 7, 8, 13, 20], then the following statements are true: nums[2:5] = = [5, 7, 8] from the subscript 2 element to the subscript 5 element, but does not contain the element labeled 5. Nums[1:] = = [3, 5, 7, 8, 13, 20] cut to the last element. NUMS[:-3] = = [1, 3, 5, 7] from the beginning of the element has been cut to the 3rd element of the bottom. nums[:] = = [1, 3, 5, 7, 8, 13, 20] returns all elements. Changing the new list does not affect the nums. Nums[1:5:2] = = [3, 7] from the subscript 1 of the element is cut to the element subscript 5 but does not contain the element labeled 5, and the step is 2.python functionsPython's functions support recursion, default parameter values, and mutable parameters, but do not support function overloading. To enhance the readability of your code, you can write a "document string" (documentation Strings, or simply docstrings) after the function to explain the function, the type and meaning of the parameter, the type of return value, and the range of values. You can use the built-in function help () to print out the use of the function. such as:>>> def Randint (A, b): ... "Return random integer in range [A, b], including both end points." ...>>> Help (Randint) to the function randint in module __main__:randint (A, b) Return random integer inrange[a, b], Including both end points.methods for Python objectsObject refers to a function that is bound to an object. The syntax for calling an object method is Instance.method (arguments). It is equivalent to calling Class.method (instance, arguments). When you define an object method, you must explicitly define the first parameter, which typically uses self, to access the object's internal data. The self here is equivalent to the this variable in C + +, Java, but we can also use any other valid parameter name, such as this and mine, and self is not exactly the same as this in C++,java, it can be seen as a habitual usage, We can pass in any other legal name, such as:?
12345678910111213141516 class Fish: def eat(self,food): if food is not None: self.hungry=Falseclass User: def__init__(myself,name): myself.name=name#构造Fish的实例:f=Fish()#以下两种调用形式是等价的:Fish.eat(f,"earthworm")f.eat("earthworm")u=User(‘username‘)print(u.name)
Python recognizes some special method names that begin with "__" and End With "__", which are used to implement operator overloading and implement a variety of special functions.python typePython uses a dynamic type system. At compile time, Python does not check whether an object has a called method or property, but is not checked until run time. Therefore, an exception may be thrown when manipulating objects. However, although Python uses a dynamic type system, it is also strongly typed. Python prohibits operations that are not explicitly defined, such as numbers plus strings. Like other object-oriented languages, Python allows programmers to define types. To construct an object, you only need to invoke the type like a function, for example, with fish () for the fish type defined earlier. The type itself is also a special type of object (the type itself is also a type object), a special design that allows for reflection programming of the type. Python has a rich data type built in. These data types effectively reduce the length of code compared to Java, C + +. The following list briefly describes Python's built-in data types (for Python 3.x):
type Description Example Notes
Str A character that consists of a serial that cannot be changed. ' Wikipedia ' "Wikipedia" "" "" Spanningmultiplelines "" In Python 3.x, strings are made up of Unicode characters
bytes A byte-composed immutable serial. B ' Some ascii ' B "Some ASCII"  
List Can contain a variety of types of can be changed with serial [4.0, ' String ', True]  
Tuple Can contain multiple types of immutable serial (4.0, ' string ', True)  
Set, Frozenset Similar to the concept of collections in mathematics. unordered, each element is unique. {4.0, ' string ', True}frozenset ([4.0, ' String ', True])  
Dict A non-serial that can be changed by a key-value pair. {' Key1 ': 1.0, 3:false}  
Int Integer with unlimited precision 42  
Float Floating-point number. Accuracy is related to the system. 3.1415927  
Complex Plural 3+2.7j  
bool Logical value. Only two values: true, False TrueFalse  
In addition to various data types, the Python language uses types to represent functions, modules, types themselves, methods of objects, compiled Python code, run-time information, and so on. As a result, Python has a strong dynamic nature.python mathematical OperationsPython uses operators similar to C and Java to support mathematical operations of integers and floating-point numbers. Integer operations are also supported for complex operations and infinite digits (which are actually limited to the computer's ability). In addition to the absolute value function abs (), most mathematical functions are in the math and Cmath modules. The former is used for real arithmetic, while the latter is used for complex operations. You need to import them first, such as the:>>> import math>>> print (Math.sin (MATH.PI/2)) 1.0fractions module to support fractional operations The decimal module is used to support high-precision floating-point arithmetic. Python defines that the value of a% B is in the open interval [0, B), and if B is a negative number, the opening interval becomes (b, 0]. This is a very common way of defining. But in fact it relies on the definition of divisible. In order for the equation to be: b * (A/b) + a% B = A constant, the division operation needs to take a value to the negative infinity direction. For example, the result of 7//3 is 2, and (-7)//3 results are-3. This algorithm is not the same as many other programming languages, and it is important to note that their division of operations will take a value in the direction of 0. Python allows two comparison operators to be written in a way that is commonly used in mathematics. For example a < b < C is equivalent to a < b and B < C. C + + does not have the same result as Python, first it calculates a < B, gets one of 0 or 12 values based on the size of the two, and then compares it to C.

Python Growth Notes-Basics (ii) Basic Python syntax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.