The for ... else
statement is used to implement search loops.
In particular, it handles the case where a search loop fails to find anything.
for z in xrange(10):
if z == 5:
# We found what we are looking for
print "we found 5"
break # The else statement will not execute because of the break
else:
# We failed to find what we were looking for
print "we failed to find 5"
z = None
print 'z = ', z
output:
we found 5
z = 5
That search is the same as
z = None
for z in xrange(10):
if 5 == z:
# We found what we are looking for
break
if z == None:
print "we failed to find 5"
else:
print "we found 5"
print 'z = ', z
Remember that for
doesn't initialize z if the search list is empty (i.e. []
). That's why we have to ensure that z is defined when we use it after the search. The following will raise an exception because z
is not defined when we try to print it.
for z in []:
if 5 == z:
break
print "z = ",z
output
print "z = ",z
NameError: name 'z' is not defined
In summary, the else
clause will execute whenever the for
loop terminates naturally. If a break or an exception occurs in the for
loop the else
statement will not execute.