"for/while ... break(by any means) ... else" make sense?

Victor Savu victor.nicolae.savu at gmail.com
Wed Jun 29 06:01:03 EDT 2016


There are many posts trying to explain the else after for or while. Here is
my take on it:

There are three ways of getting out of a (for/while) loop: throw, break or
the iterator gets exhausted. The question is, how cab we tell which way we
exited? For the throw, we have the except clause. This leaves us to
differentiatr between break and normal exhaustion of the iterator. This is
that the else clause is for: we enter the body iff the loop iterator was
exhausted.

A lot of discussion goes around the actual keyword used: else. Opinions may
differ,  but I for one would have chosen 'then' as a keyword to mark
something that naturally happens as part of the for statement but after the
looping is over; assuming break jumps out of the entire statement, it makes
sense that it skips the 'then' body as well. (In the same way, I prefer
'catch' to 'except' as a correspondent to 'throw', but all of this is just
bikeshedding). At a language design level, the decision was made to reuse
one of the existing keywords and for better or worse, 'else' was chosen,
which can be thought of as having no relation to the other use of the same
keyword in the 'if' statement. The only rationale behind this was to save
one keyword. The search analogy often used for justifying 'else' is (to me)
totally bogus, since the same argument can be used to support replacing the
keyword 'for' by the keyword 'find' and have looping only as a side-effect
of a search.

I hope this gives you some sense of closure.


Best,
VS



More information about the Python-list mailing list