python cycling conditions - conditions

 

1. Conditions and loops

 

The main discussion: if, while, for, and associated with else, elif, break, continue and pass sentence.

1.1 if statement

if statement consists of three parts: the keyword itself, for the true and false judgment result of the conditional expression, and the judgment is true or non-zero blocks of code executed, the following syntax:

if expression:

    expr_true_suite

1.2 Multiple conditional expression

Single multiple if statements may be implemented using the determination condition and, or, not like.

if experssion1 and expression2:

    expr_true_suite

1.3 a single block of code statements

If a complex sentence (IF statement, while, or for loop) code block contains only one line of code, and the previous statement can be written on the same line. For convenience readable, generally do not write.

if expression: expr_true_suite

1.4 else statements

if statements and else statements can be used in conjunction with, if it is judged to be false, the else statement is called. The syntax is as follows:

if expression:

  expr_true_suite

else:

  expr_false_suite

Special usage: You can use the while and for loop else statement, when used in a loop, else clause is executed only after the cycle is complete, that is to say the break statement will skip the else block . Cycle is completed normally (not by the break), else clause is executed.

 1 #!/usr/bin/env python
 2 
 3 def showMaxFactor(num):
 4     count = num/2
 5     while count > 1:
 6         if num % count == 0:
 7             print 'largest factor of %d is %d' % (num, count)
 8             break
 9         count -= 1
10     else:
11         print num, 'is prime'
12 
13 if __name__ == '__main__':
14     for eachNum in range(10, 21):
15         showMaxFactor(eachNum)
16 
17 [root@localhost python]# python maxFact.py 
18 largest factor of 10 is 5
19 11 is prime
20 largest factor of 12 is 6
21 13 is prime
22 largest factor of 14 is 7
23 largest factor of 15 is 5
24 largest factor of 16 is 8
25 17 is prime
26 largest factor of 18 is 9
27 19 is prime
28 largest factor of 20 is 10

1.5 elif (i.e. else-if statement)

elif statement for checking whether a plurality of expression is true, and is true when the code execution code block. The syntax is as follows:

if expression1:

  expr1_true_suite

elif expression2:

  expr2_true_suite

elif expression:

  exprN_true_suite

else:

  none_of_the_above_suite

Can use a lot of if-elif statement to implement switch-case statement, it can also be used to implement sequence and membership, can also use the dictionary to achieve.

1.6 The conditional expression (i.e. "ternary operator")

Similar to the C language C X:? Y (C is an expression, X is the result when the True C, Y is the result when the False C). The python syntax is: X if C else Y.

>>> x, y = 4, 3

>>> smaller = x if x < y else y

>>> smaller

3

Guess you like

Origin www.cnblogs.com/mrlayfolk/p/12000494.html