I learned it according to the documentation attached to Python 2.5. The document is very long and it is in English. I think it will be inconvenient to search for it later, so I will record what I have learned here. I already know more basic things about Python, so I will omit them here. Start from the newer part.
If statement
Problem: read an integer N from the keyboard and output SGN (n ).
X = int (raw_input ("input an integer :"))
If X = 0:
Print 0
Elif x> 0:
Print 1
Else:
Print-1
This example is very simple. It is no different from other languages, and its usage is the same. Note that Elif is short for else if.
For statement
Problem: print the string in a list and the length of each string.
A = ['cat', 'window', 'deletestrate']
For X in:
Print X, Len (X)
This code is simpler. Note that the in operator can be used to enumerate list elements.
Problem: insert the elements with a length greater than 6 in the list string to the list header and output them in sequence.
A = ['cat', 'window', 'deletestrate']
For X in a [:]:
If Len (x)> 6:
A. insert (0, x)
For X in:
Print x
The first loop uses for X in a [:]. The Python document assumes that it is unsafe to directly modify a sequence in the loop and then enumerate, if you need to modify it, generate a copy, and then enumerate it in this copy.
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists ). if you need to modify the list you are iterating over (for example, to duplicate selected items) You must iterate over a copy. the Slice notation makes this special convenient.
Range () function
The range () function can generate an equal-difference series. For example, the result of range (n) is ~ List of All integers in n-1, range (m, n) results in a list of all integers in [m, n), while range (m, n, d) it indicates the list with the D as the tolerances starting from m and not exceeding n-1.
Break and continue statements, and else statements used together with cyclic statements
The roles of break and continue are the same as those in C.
It is worth noting that the for and while statements can be combined with the else-guided statements. Obviously, it means the operation executed when the loop condition is no longer set. The example in this document is a program used to determine whether each integer in [2, 10) is a prime number.
For N in range (2, 10 ):
For X in range (2, n ):
If n % x = 0:
Print N, 'eques', X, '*', N/x
Break
Else:
Print N, 'is a prime number'
Pass statement
A pass statement is equivalent to an empty statement.
ThePassStatement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
While true:
Pass # Busy-wait for keyboard interrupt