for what are for/while else clauses

Alex Martelli aleax at aleax.it
Mon Nov 17 11:41:27 EST 2003


Alexander Schmolck wrote:

> Alex Martelli <aleax at aleax.it> writes:
>> Python could presumably help a little by warning about an 'else' on
>> a for or while loop that contains no 'break' statements.  But the
>> reason Python's for/else and while/else statements are not intuitive
>> to most people can be boiled down to identifying that "controlling
>> condition" -- the fact that the 'controlling condition' is "a break
>> statement has executed" is """hardly obvious or most particularly "the
>> only obvious" interpretation""", to repeat myself:-).
> 
> Hmm, I can't see the break here:
> 
>>>> for x in []: print 'something'
> ... else: print 'nothing'
> ...
> nothing

Exactly because there is no 'break' in the loop's body, the 'else: '
clause-header is useless in this case; the code:

for x in []: print 'something'
print 'nothing'

(where the second print follows the whole loop rather than being
the body of its 'else' clause) would be quite equivalent.

> (Not that I wouldn't argue that the semantics of else in loops are
> blindingly obvious, but I can see the (albeit slightly strained) analogy
> with if/else).

If I squint hard enough I can see the similarity, sure, but I keep
thinking that "how do I _USE_ this language feature" is a more generally
useful viewpoint than "how is this language feature implemented".  And
the (modest) _usefulness_ of the else clause on for and while loops is
inevitably connected to the possibility that a 'break' in the loop's
body may execute.  If there is no such possibility, you might as well
just code the statements right after the whole loop, rather than putting
them in an else clause.


Alex





More information about the Python-list mailing list