for: else: - any practical uses for the else clause?

Sion Arrowsmith siona at chiark.greenend.org.uk
Thu Sep 28 11:26:34 EDT 2006


Ben Sizer <kylotan at gmail.com> wrote:
>skip at pobox.com wrote:
>> Yeah, I use it from time to time:
>>
>>     for foo in bar:
>>         if foo matches some condition:
>>             print "sail to tahiti!"
>>             break
>>     else:
>>         print "abandon ship!"
>
>As a C++ programmer (which I'm sure undermines my argument before
>you've even read it...), this feels 'backwards' to me. Although I am no
>purist, the 'else' typically implies failure of a previous explicit
>condition, yet in this case, it's executed by default, when the
>previous clause was successfully executed. It would seem more natural
>if the else clause was triggered by 'bar' being empty, [ ... ]

It does:

>>> for foo in []:
...     print foo
... else:
...     print 'else'
...
else

I think it's clearer to see by comparing while with if:

if False:
    do nothing
else:
    do something

while False:
    do nothing
else:
    do something

and getting to the for behaviour from while is trivial.

That said, I've not had much call for it and was kind of surprised to
find myself writing a genuine for ... else the other week. But it was
the obvious way to do the task at hand, and I was happy it was there.

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list