0. Description
The references are: if, while, for and the else, elif, break, continue, and pass statements that match them.
1.if statements
If Expression:expr_true_suite
In the expression section, you can use logical join words an, or and not to achieve multiple judgment conditions.
That is, if only one statement executes, it can be written as follows:
If True:print ' OK '
But it is still recommended to write on different lines.
2.else statements
If Expression:expr_true_suiteelse:expr_false_suite
This is the case in languages like C, which use parentheses to separate blocks of code (that is, if frogs have multiple if statements, the Else statement does not know which of the IF statements are), but because Python enforces the use of indentation to align the code, this problem is unlikely to occur.
3.elif statements
If Expression1:expr1_true_suiteelif expression2:expr2_true_suiteelif expression3:expr3_true_suite ... elif expressionN:expr1_true_suiteelse:none_of_the_above_suite
There can be any number of elif statements, but there can be only one else statement.
There are switch/case statements in C that are used to choose among multiple options, although Python does not have a switch/case statement, but there is a better solution to achieve the same functionality:
#方案一: A large number of IF-ELIF statements if user.cmd == ' create ': action = ' create item ' elif user.cmd == ' delete ': action = ' Delete item ' elif user.cmd == ' Update ': action = ' update item ' # Scenario two: Using the sequence and membership operator if user.cmd in (' Create ', ' delete ', ' update '): action = '%s item ' % user.cmdelse: action = ' invalid choice... try again! ' #方案三: Using the dictionary msgs = {' Create ', ' Create item ', ' delete ': ' Delete item ', ' Update ': ' Update item '}default = ' invalid choice... try again! ' Action = msgs.get (User.cmd, default) # One of the biggest benefits of using a mapped object, such as a dictionary, is that its search operation is much faster than a sequence query like a if-elif-else statement or a for loop.
As you can see, the solution in Python is more powerful and concise for implementing the same functionality.
4. Conditional expressions (ternary operators)
Use the following:
>>> x, y =4, 3>>> smaller = x if x < y else y>>> Smaller3
5.while statements
While Expression:suite_to_repeat
Count = 0while (Count < 9): print ' The index is: ', count count + = 1
While True:suite_to_repeat
The infinite loop is mainly used in the design of the server side of the server/client mode to wait for a connection from the client, although it is possible to end the loop with a break statement if necessary.
6.for statements
The For statement provides the most powerful loop structure in Python, which iterates through the sequence members and can be used in list resolution and generator expressions, which automatically invokes the next () method of the iterator, captures the stopiteration exception, and ends the loop (all of this happens internally).
(1) syntax
For Iter_var in Iterable:suite_to_repeat
For Each loop, the Iter_var-stroke iteration variable is set to iterate over the current element of the object iterable (sequence, iterator, or other object that supports iterations), which is provided to the Suite_to_repeat statement for use.
(2) for sequence type
Here are three ways to iterate over the sequence:
>>> namelist = [' xpleaf ', ' clyyh ', ' cl ']>>> for name in NameList: ... print name ... xpleafclyyhcl
>>> namelist = [' xpleaf ', ' clyyh ', ' cl ']>>> for Nameindex in range (len (namelist)): ... print namelist[n Ameindex] ... xpleafclyyhcl
is obviously much slower than the first method.
>>> namelist = [' xpleaf ', ' clyyh ', ' cl ']>>> for Nameindex, name in Enumerate (namelist): ... print Namei Ndex, name ... 0 XPLEAF1 CLYYH2 CL
(3) for iterator type
When used with iterators, the For statement automatically handles many problems (calling next () internally and handling the stopiteration exception), but it is important to note that iterators do not represent a collection of circular entries.
(4) range () built-in function
Range () can be used to generate a list of numeric orders that can be iterated using for, which mainly has the following two syntax:
As follows:
Range (start, end, Step=1)
That is, the default step is 1, for example:
>>> Range (1) [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range (1, 10, 3) [1, 4, 7]
However, the step size cannot be 0, otherwise an error occurs:
>>> Range (1, 0) Traceback (most recent): File ' <stdin> ', line 1, in <module>valueerror: Range () Step argument must not is zero
Range (end) #即默认start =1range (start, end) #其实就是默认步长为1的情况
Examples are as follows:
>>> range [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range (0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(5) Xrange () built-in function
When range () is called, a list is generated and written to memory, but when the resulting list is large, using range () is not appropriate, so you can consider xrange (), which returns an iterative object and does not generate a complete list, so it is used only in the For loop , otherwise it doesn't make sense:
>>> xrange xrange (Ten) >>> type (xrange) <type ' xrange ' >>>> for num in xrange (10) :... print num,... 0 1 2 3 4 5 6 7 8 9
(6) Built-in functions related to sequences
Mainly:sorted (),reversed (),Enumerate (),zip ()
This is related to the sequence because two of the functions (sorted () and zip ()) return a sequence (list), while the other two functions (reversed () and enumerate ()) return iterators, for example:
>>> nametuple = (' Xpleaf ', ' cl ') >>> years = (1994, 1995) >>> sorted (nametuple) [' cl ', ' xpleaf '] >>> for name in sorted (nametuple):.. Print name,... cl Xpleaf
>>> reversed (nametuple) <reversed object at 0x7f2fa02df390>>>> for name in reversed (nametuple): ... print name,... cl Xpleaf
>>> Enumerate (nametuple) <enumerate object at 0x7f2f9e1c1d20>>>> for Nameindex, name in Enumerate (nametuple): ... print nameindex, name ... 0 XPLEAF1 CL
>>> Zip (Nametuple, years) [(' Xpleaf ', 1994), (' CL ', 1995)]>>> for name, year in Zip (Nametuple, years): ... . Print name, year ... xpleaf 1994CL 1995
7.break statements
Break can end the current loop and then jump to the next statement (if one exists), which can be used for both the while and for two loops:
>>> count = 0>>> while True: ... if count>10: ... print ' OK ' ... break ... count + = 1 ... Ok
8.continue statements
Continue statement: When a ontinue statement is encountered, the program terminates the current loop, ignores the remaining statements, and then returns to the top of the loop. Before starting an iteration, if it is a conditional loop, we will validate the conditional expression, and if it is an iterative loop, we will verify that there are elements that can iterate . The next iteration is only started if the validation succeeds.
In Python, the while loop is conditional and the For loop is iterative, which corresponds to the two cases above, and can be simply exemplified as follows:
>>> count = 0>>> while count<10: ... count + = 1 ... If count! = 6: ... continue ... print count ... 6>>>>>> for count in range: ... if count! = 6: ... continue ... print count ... 6
9.pass statements
The pass statement is used mainly in the following areas:
Some places require code in grammar.
tag the code that will be finished later (such as defining a class or function first, but doing nothing)
In exception handling, it is possible to pass directly to an exception that has little impact
10. Again the Else statement
In Python, in addition to using else in a conditional statement, you can also use the Else statement in the while and for loops. When used in a loop, the ELSE clause executes only after the loop completes, that is, if a break statement exists in the loop, the Else statement is skipped.
For example: Looking for a number of the maximum approximate
#!/usr/bin/env pythondef showmaxfactor (num): count = num / 2 #从一半开始计数 so you can check if this number is divisible by 2, and if you can, find the largest approximate while count > 1: if num % count == 0: print ' largest factor of %d is %d ' % (num, count) break count -= 1 else: print num, ' is prime ' if __name__ == ' __main__ ': showmaxfactor ( showmaxfactor (+)
This is a very good feature, you can think about it, if you do not have this feature, to achieve the above function, logically it is definitely not so clear.
This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1754975
Python Review and Collation 6: conditions and loops