for-else

Carl Banks pavlovevidence at gmail.com
Tue Mar 4 10:17:39 EST 2008


On Mar 4, 8:27 am, bearophileH... at lycos.com wrote:
> So far in Python I've almost hated the 'else' of the 'for' loops:
> - I have problems to remember its meaning;
> - It gives me little problems when I later want to translate Python
> code to other languages (and you always have to translate long-lived
> code).
> - I have used it only once, so far.
>
> So so far I'd liked to see it removed from Python 3.0.
>
> But then this article:http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel...
> has shown me that my problems with the 'else' of the 'for' mostly come
> from just its bad naming. The converge language is yet another very
> Python-like language, and it uses a better naming (the word
> "exhausted" is long and has a complex spelling for non-English
> speakers, so it's not perfect):
>
> for ...:
>     ...
> exhausted:
>     ...
> broken:
>     ...
>
> The meaning is explicit. While "else" seems to mean little there.
> So I may like something similar for Python 3.x (or the removal of the
> "else").


I would not be opposed to this on its own merits, but there is a
rationale behind the name "else".  If you consider a for loop to be a
rolled-up if...elif...else statement (situations where this is
reasonable tend to be the same ones were else would be useful), then
the "else" clause would remain unchanged on the for loop.

For instance, if you have a (trivial) if...elif...else like this:

if a == 0:
    do_task_0()
elif a == 1:
    do_task_1()
elif a == 2:
    do_task_2()
else:
    do_default_task()

You could roll it up into a for...else statement like this:

for i in range(3):
    if a == i:
        do_task[a]()
else:
    do_default_task()

(Please never mind the trivialness of this example; I know you can
eliminate the for loop altogether; this is JUST an example.)

I keep this analogy in mind when using for...else to keep the
semantics straight.


Carl Banks



More information about the Python-list mailing list