for: else: - any practical uses for the else clause?
Johan Steyn
johan.steyn at gmail.com
Fri Sep 29 17:17:34 EDT 2006
On 29 Sep 2006 11:26:10 -0700, Klaas <mike.klaas at gmail.com> wrote:
> else: does not trigger when there is no data on which to iterate, but
> when the loop terminated normally (ie., wasn't break-ed out). It is
> meaningless without break.
The else clause *is* executed when there is no data on which to iterate.
Your example even demonstrates that clearly:
>>> for x in []:
> ... print 'nothing'
> ... else:
> ... print 'done'
> ...
> done
The else clause is executed because the loop still terminates normally with
an empty list - albeit without having looped at all.
I agree that it is meaningless without a break statement, but I still find
it useful when I want to determine whether I looped over the whole list or
not. For example, if I want to see whether or not a list contains an odd
number:
for i in list:
if i % 2 == 1:
print "Found an odd number."
break
else:
print "No odd number found."
Without the else clause I would need to use an extra variable as a "flag"
and check its value outside the loop:
found = False
for i in list:
if i % 2 == 1:
print "Found an odd number."
found = True
break
if not found:
print "No odd number found."
OK, so using "else" only saves me 2 lines and a variable - not much to write
home about, but I still like it.
Johan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060929/07c5b1b9/attachment.html>
More information about the Python-list
mailing list