"for" with "else"?
Michael Geary
Mike at DeleteThis.Geary.com
Thu Sep 25 12:55:13 EDT 2003
Mark Jackson wrote:
> (This happens to be the *reverse* of what my intuition expects - it
> would seem more natural if the syntax meant "do this for loop to
> completion, else do this extra stuff," but this is the way it is and
> one must simply remember it.)
I'm with you there--the use of "else" here has seemed a bit confusing to me.
The use case that Alex just posted gave me another way to think about it:
for item in allitems:
if fraboozable(item):
print "first fraboozable item is", item
break
else:
print "Sorry, no item is fraboozable"
If I think of the else statement as being related to the if statement inside
the loop, then it makes some sense--the else statement is executed when the
if statement never comes up true. (It's twisted logic, I know, but at least
it helps me keep track of what "else" does here.)
-Mike
More information about the Python-list
mailing list