Analysis of the use of else statement blocks in Python, analysis of pythonelse statements
All those who have learned C/C ++ know that else statements are used with if statements, but in Python, else statements are more like a module, not only can they be used with if statements, it can also be used with loop statements and Exception Handling statements.
Next we will introduce them one by one:
<1> if statement
When the condition expression is true, run code block 1. Otherwise, run code block 2)
If... else... extension mode: Multiple if conditions are determined, as shown in figure: the execution of the entire code block ends along certain arrows (black spots in the figure ).
Note that EXPRESSIONS 1, 2, and 3 have priority, from high to low. Therefore, for some applications, the efficiency of determining conditions with high probability is relatively high.
For example, the score distribution of the class is 80 ~ The probability of the number of students in the 60 interval is high. If you want to score ABCD scores for the students in the class, you should first judge the probability range.
<2> while, for loop statement
In Python, loop statements (both while and for) often work with the continue and break statements. The difference between the two is not described here.
In addition, it can be used with the else statement block. When the loop ends normally, the else statement block is executed again. If the loop ends normally (for example, the break statement jumps out, otherwise, the else statement block is not executed.
# Calculate the maximum common approx. def get_max_factor (arg): cnt = arg/2 while cnt> 1: if arg % cnt = 0: print "Max factor of % s is % s" % (arg, cnt) break cnt-= 1 else: print "% s is prime. "% argif _ name _ =" _ main _ ": for I in range (10, 20): get_max_factor (I) ######### result ############ Max factor of 10 is 511 is prime. max factor of 12 is 613 is prime. max factor of 14 is 7Max factor of 15 is 5Max factor of 16 is 817 is prime. max factor of 18 is 919 is prime.
The code above indicates that when the loop Exits normally, arg will not be 2 ~ The else statement block is executed only when any integer between arg and 2 is divisible. This also shows that arg is a prime number.
<3> try:... esle :.....
The above section describes how to use else statement blocks in Python. I hope to help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!