On 29 Sep 2006 11:26:10 -0700, Klaas <[EMAIL PROTECTED]> 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.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to