else clause in the [Python] looping statement
Programmers with other programming languages experience the most surprising thing about Python is the ubiquitous else, not only branching statements, but also looping statements, and even exception handling. But now let's look at the else in the looping statements to see their syntax: while_stmt::= "While" expression ":" suite ["Else" ":" Suite]for_stmt::= "for" target_list "in" expression_list ":" suite ["Else" ":" suite] to talk about the ELSE clause, you have to know that Python borrows the same semantic break and continue statements from the C language, because the ELSE clause provides an implicit statement that the loop is triggered by a break clause that causes the loop to end. Judge. Let's take a look at an example where the ELSE clause is not applied:>>> def print_prime (n):... for I in xrange (2, N): .... & nbsp; found = true... for J in Xrange (2, i):... if I% j = = 0:... found = false... break... if found:... print '%d is a prime number '% I this is a simple implementation to find the prime number, we can see that we use a flag amount found to determine whether the loop end is caused by the break statement, if the else is good use, the code can be much simpler:>>> def print_prime2 (n): ... for I in xrange (2, N):... for J in Xrange (2, i):... if I% j = = 0:... break... Else: ... print '%d is a prime number '%i when the "natural" end of the loop (the loop condition is false) The ELSE clause is executed once, and if the loop is interrupted by a break statement, the ELSE clause is not executed. is similar to a for statement, while the ELSE clause of the while statement has the same semantics. Else blocks are executed when the loop is normal and the loop condition is not established. compared to "old-fashioned" languages like C + +, the ELSE clause improves the productivity of programmers and the readability of code. Still, I haven't seen much in the code that uses the ELSE clause, presumably because everyone is used to the C-type marker solution, and I recommend that you use else more. For the last gossip, if you want to exit multiple loops directly in Python, you should use exceptions, and Python does not provide Goto. Next time we'll talk about the anomaly.
Use "Go" for else in Python