"for" with "else"?
Alex Martelli
aleax at aleax.it
Thu Sep 25 10:01:04 EDT 2003
Invalid User wrote:
> While trying to print a none empty list, I accidentaly put an "else"
> statement with a "for" instead of "if". Here is what I had:
>
> if ( len(mylist)> 0) :
> for x,y in mylist:
> print x,y
> else:
> print "Empty list"
>
> which was supposed to be:
>
> if ( len(mylist)> 0) :
> for x,y in mylist:
> print x,y
> else:
> print "Empty list"
>
>
> Is this to be expected?
Sure. The else branch is executed unless the for terminates
prematurely (via break, return or exception) -- just like the
else branch of a while loop.
Typical use case:
for item in allitems:
if fraboozable(item):
print "first fraboozable item is", item
break
else:
print "Sorry, no item is fraboozable"
Alex
More information about the Python-list
mailing list