What are the syntaxes and types you must understand when getting started with Python?

Source: Internet
Author: User

One of Python's design goals is to make the source code highly readable. It tries its best to use punctuation marks and English words frequently used in other languages during the design, so that the source code looks neat and beautiful as a whole. Unlike static languages such as C and Pascal, which require repeated Writing of statement statements, it is not as often as special cases and surprises as their syntax.

Indent

Python developers intentionally prevent programs that violate indentation rules from being compiled to force programmers to develop good programming habits. In Python, indentation is used to indicate the start and exit of the statement block instead of curly braces or certain keywords. Adding indentation indicates the beginning of the statement block, while reducing indentation indicates the exit of the statement block. Indentation is part of the syntax. For example

If statement:

 
 
  1. If age <21:
  2. Print ("You cannot drink. ")
  3. Print ("but you can stick gum. ")
  4. Print ("this sentence is outside the if sentence. ")

According to PEP4 spacesEach level of indentation. Although tabs and other spaces can be compiled, they do not conform to the encoding rules. The support for Tab characters and other spaces is only for compatibility with old Python programs and some problematic editors.

Statements and Control Flow

◆ If statement. When the condition is set, execute the statement block. It is often used with else and elif (equivalent to else if.

◆ For statement, which traverses the list, String, Dictionary, set, and other iterators and processes each element in the iterator in sequence.

◆ While statement. When the condition is true, the statement block is executed cyclically.

◆ Try statement. Works with mongot and finally to handle exceptions that occur during the program running.

◆ Class statement. Defines the type.

◆ Def statement. Defines functions and types.

◆ Pass statement. This action is null and no operation is performed.

◆ Assert statement. Used to test whether the running conditions are met during program debugging.

◆ With statement. The syntax defined after Python2.6 runs statement blocks in a scenario. For example, lock the block before running the statement and release it after it is finished.

◆ Yield statement. Used in the iterator function to return an element. Since Python 2.5. This statement becomes an operator.

Expression

The expression in Python is similar to that in C/C ++. However, there are differences in some writing methods.

◆ The main arithmetic operators are similar to C/C ++. + ,-,*,/,//,**,~, % Indicates addition, subtraction, positive subtraction, or negative addition, multiplication, division, division, multiplication, population, and modulo. >>>, <Indicates shift right and shift left. &, |, ^ Indicates the AND, OR, XOR operations of binary.>, <, = ,! =, <=, >= Is used to compare the values of two expressions, indicating greater than, less than, equal to, not equal to, less than or equal to, and greater than or equal. In these operators ,~, |, ^, &, <,> Must be an integer.

◆ Python uses and, or, not to represent logical operations.

◆ Is, is not is used to compare whether two variables are the same object. In, not in is used to determine whether an object belongs to another object.

◆ Python supports list comprehension, for example, calculating the sum of squares of 0-9:

 
 
  1. >>> sum(x * x for x in range(10))285 

◆ Python uses lambda to represent anonymous functions. The anonymous function body can only be an expression. For example:

 
 
  1. >>> add=lambda x, y : x + y>>> add(3,2)5 

◆ Python uses y if cond else x to represent conditional expressions. If cond is true, the expression value is y; otherwise, the expression value is x. Is equivalent to cond in C ++ and Java? Y: x.

◆ Python lists and tuple. List is written as [1, 2, 3], while tuple is written as (1, 2, 3 ). You can change the elements in the list but not tuple. In some cases, the brackets of the tuple can be omitted. Tuple has special processing for the value assignment statement. Therefore, you can assign values to multiple variables at the same time, for example:

 
 
  1. >>> X, y = 1, 2 # assign values to x and y at the same time. The final result is: x = 1, y = 2.

◆ In particular, you can exchange the values of two variables in the following form:

 
 
  1. >>> X, y = y, x # final result: y = 1, x = 2

◆ Python uses '(single quotes) and "(double quotes) to represent strings. Unlike Perl, Unix Shell, Ruby, Groovy, and other languages, the two symbols work the same. Generally, if a string contains double quotation marks, the string is represented by single quotation marks. Otherwise, double quotation marks are used. If none of them appear, you can choose according to your personal preferences. The \ (backslash) in the string is interpreted as a special character. For example, \ n indicates a line break. Add r before the expression to indicate that Python does not interpret the \ in the string \. This method is usually used to write regular expressions or Windows File paths.

◆ Python supports list slices to obtain a complete list. The following types are supported: str, bytes, list, And tuple. 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], the following statements are true:

◆ Nums [2: 5] = [5, 7, 8] Cut from an element whose subscript is 2 to an element whose subscript is 5, but does not contain an element whose subscript is 2.

◆ Nums [1:] = [3, 5, 7, 8, 13, 20] Cut to the last element.

◆ Nums [:-3] = [1, 3, 5, 7] Cut from the first element to the last 3rd elements.

◆ Nums [:] = [1, 3, 5, 7, 8, 13, 20] returns all elements. Changing the new list does not affect nums.

◆ Nums [] = [3, 7]

Function

Python Functions Support recursion, default parameter values, and variable parameters, but do not support function overloading. To enhance code readability, you can write the "Documentation Strings" (docstrings) after the function ), it is used to explain the functions, types and meanings of parameters, return value types and value ranges, and so on. You can use the built-in function help () to print out the function help. For example:

 
 
  1. >>> def randint(a, b):  
  2.  ...     "Return random integer in range [a, b], including both end points." 
  3.  ...  
  4.  >>> help(randint)  
  5.  Help on function randint in module __main__:  
  6.     
  7.  randint(a, b)  
  8.      Return random integer in range [a, b], including both end points. 

Object Method

An object is a function bound to an object. The syntax for calling object methods is instance. method (arguments ). It is equivalent to calling Class. method (instance, arguments ). When defining an object method, you must explicitly define the first parameter as self to access the internal data of the object. Self is equivalent to the this variable in C ++ and Java. For example:

 
 
  1. Class Fish:
  2. Def eat (self, food ):
  3. If food is not None:
  4. Self. hungry = False
  5. # Construct a Fish instance:
  6. F = Fish ()
  7. # The following two call forms are equivalent:
  8. Fish. eat (f, "earthworm ")
  9. F. eat ("earthworm ")

Python recognizes some special method names starting with "_" and ending with "_". They are used to implement Operator Overloading and implement various special functions.

Type

Python uses a dynamic type system. During compilation, Python does not check whether the object has the called method or attribute, but does not check until it is running. Therefore, an exception may be thrown during object operations. However, although Python uses a dynamic type system, it is also strongly typed. Python prohibits unspecified operations, such as adding numbers to strings.

Like other object-oriented languages, Python allows programmers to define types. To construct an object, you only need to call the type like a function. For example, for the previously defined Fish type, use Fish (). The type itself is also a special type object (the type itself is also a type object), this special design allows reflection programming on the type.

Python has a wide range of built-in data types. Compared with Java and C ++, these data types effectively reduce the code length. The following list briefly describes the Python built-in data types (applicable to Python 3.x ):

In addition to various data types, the Python language also uses types to represent functions, modules, types, object methods, compiled Python code, runtime information, and so on. Therefore, Python is highly dynamic.

Mathematical operations

Python uses operators similar to C and Java to support mathematical operations on integers and floating-point numbers. At the same time, it also supports the complex operation and the Integer Operation of the infinite number of digits (actually limited by the ability of the computer. In addition to the absolute value function abs (), most mathematical functions are in the math and cmath modules. The former is used for real operations, while the latter is used for complex operations. You must first import them for use, for example:

 
 
  1. >>> import math  
  2. >>> print(math.sin(math.pi/2))  
  3. 1.0 

The fractions module is used to support fractional operations. The decimal module is used to support high-precision floating-point operations.

Python defines that the value of a % B is in the open range [0, B). If B is a negative number, the open range is changed to (B, 0]. This is a common definition method. However, it depends on the entire division definition. In order to let the equation: B * (a/B) + a % B = a constant, the operation of the entire Division must be in the negative infinity direction. For example, the result of 7 // 3 is 2, while the result of (-7) // 3 is-3. This algorithm is different from many other programming languages. Note that their Division operations take a value in the direction of 0.

Python allows two comparison operators to be written in parallel like a common mathematical statement. For example, a <B <c is equivalent to a <B and B <c. The result of C ++ is different from that of Python. First, it calculates a <B, obtains one of the values 0 or 1 based on the size of the two, and then compares them with c.

Original article: http://www.cnblogs.com/mcdou/archive/2011/08/02/2125016.html

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.