Entry
Of what use is the "else" clause in "for" and "while" loops and "try" statements?
Jun 20th, 2002 07:33
Michael Chermside, Ville Vainio, Derek Thompson, Fredrik Lundh
Many python programmers are not even aware that "for" and "while" loops
and "try" statements have an optional "else" clause. Code in this clause
is executed after the loop completes, but skipped if the loops is exited
via "break" or the "try" is exited via exception.
The clause is good for searching, and saves mucking about with flags to
achieve the same effect.
Here are some sample uses (thanks to Fredrik Lundh):
for item in list:
if item == my_target:
print "found it"
process(item)
break
else:
print "not found"
while more_items():
item = get_next_item()
if item == my_target:
print "found it"
process(item)
break
else:
print "not found"
try:
item = lookup(database, key)
except KeyError:
print "not found"
else:
print "found"
process(item)
try:
handler = getattr(object, "handler")
except AttributeError:
print "no handler"
else:
handler(event)