for what are for/while else clauses

Alex Martelli aleax at aleax.it
Mon Nov 17 05:22:35 EST 2003


Fredrik Lundh wrote:

> Alex Martelli wrote:
> 
>> (taking "else" to mean "no break was executed in the body" is hardly
>> obvious or most particularly "the only obvious" interpretation).
> 
> that's not what it means, of course.
> 
> in every single case, it means "run once, if and only if the
> controlling condition is false".
> 
> </F>

I'm not sure what you mean by "the controlling condition" in this case.

In a for/else or while/else construct, the only way to make your
assertion true is to define "the controlling condition" as "a break
[or return] interrupted the for or while loop [or an exception was
propagated]" -- basically (quibbles on returns and exceptions apart)
just what I said about "no break was executed".

A reasonably-common newbie error is to code, for example:

for purchase in purchases:
    print 'Purchased:', purchase
else:
    print "Nothing was purchased"

taking "the controlling condition" to be the obvious one, i.e., the
sequence the 'for' is iterating on.  Or, similarly:

while current_value < threshold:
    process_high_value(current_value)
    current_value = compute_next_value()
else:
    alert_no_high_values(threshold)

taking "the controlling condition" to be the obvious one, i.e., the
"current_value < threshold" conditions that controls the 'while'.

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:-).


Alex





More information about the Python-list mailing list