[Tutor] for/else question

Gabriel Cooper gabriel.cooper at mediapulse.com
Thu Sep 11 20:03:12 EDT 2003


python has this weird "else" after a for loop, like so:

for x in y:
    do stuff
else:
    do other stuff

At first glance I thought this was really cool. Instead of hanging onto 
"found = 1" variables like in C, I could just throw on this handy else 
and (I presumed) it would, if my for loop never resulted in a success, 
automatically kick in. But no, that's not the case. So I thought that it 
would hit the else if you broke out of the for loop (so, perhaps, like 
catching an exception). But no, that's not the case either. It turns out 
that it always uses the else unless you break out of your loop. So it's 
not really an else, it's more like an "if I didn't die in my loop" 
catch. What use is that?

It would seem that the use is so that if you're running through a for 
loop and are trying to /find something/ rather than /do something/ then 
if you didn't find what you were looking for (and thus didn't break) 
then you can set variables appropriately, e.g.:

for x in (a,b,c):
    if x == y:
       variable = something
       break
else:
    aw shucks, didn't find anything.
    variable = 0

But that's lame for a couple of reasons: first, how often do you use a 
for loop to /look for stuff/ instead of /do stuff/? Secondly, isn't 
breaking out of a loop considered "bad programming"? Much like GOTO's? 
Finally, in the example above you would have simply set 'variable' to 
zero to begin with, so you wouldn't use the else anyway!

So... yeah... Do /you/ use "else" with for loops? If so, when?

=]




More information about the Tutor mailing list