A while or for loop in Python can be followed by an else clause, which serves the purpose of executing an else statement at the end of the for loop if the if condition is never satisfied.
for i in range(5): if i == 1: print 'in for' else: print 'in else' print 'after for-loop' # in for # in else # after for-loop
But we find that the if condition holds during the loop, and we end up executing the contents of the else statement, why is that?
Okay, let's look at the following program at this point:
for i in range(5): if i == 1: print 'in for' break else: print 'in else' print 'after for-loop' # in for # after for-loop
We added a break to the if, this is because else is executed after for, but the else statement is only executed when the for loop exits normally (not when the loop is ended by a break). And when the loop is interrupted by a break statement, else is not executed.
The for/else equivalent is the following code, which can be used to add a flag in a C-like manner:
found = False for i in range(5): if i == 1: found = True print 'in for' if not found: print 'not found' print 'after for-loop' # in for # after for-loop
Similar to the for statement, the use of the else clause in the while statement is the same; the else block is executed at the normal end of the loop and when the loop condition does not hold.
We're familiar with conditional if- else statements, but in Python, for-else is used to handle traversal failures.
For example, we want to implement a function that finds the largest perfect square number in (81, 99) and outputs it, or outputs a hint if it can't be found.
If you implement it with a C++ for loop, you must manually determine if the for loop fails to traverse:
#include <iostream> #include<> using namespace std; int main() { int i; float n; for(i=99;i>81;i--) { n=sqrt((float)i); if(n==int(n)) { cout<<i; break; } } if(i==81) // Boundary judgment cout<<"didn't find it!"<<endl; return 0; }
This is simply accomplished with Python's for-else:
from math import sqrt for n in range(99,81,-1): root = sqrt(n) if root == int(root): print n break else: print"Didn't find it!"
Execute else only after the for loop is complete; if you jump out of break in the middle, you jump out with else.
In particular, it should be noted that if there is an if statement in the for, the indentation of the else must be aligned with the for. If aligned with the if, it will become an if-else statement, which will produce unexpected errors as follows:
from math import sqrt for n in range(99,81,-1): root = sqrt(n) if root == int(root): print n break else: print"Didn't find it!"
Although using for-else saves two lines of code and is easy to read, it is easily confused with if-else. It doesn't seem to be commonly used in practice, and is preferred to be handled manually.