[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses

Bruce Leban bruce at leapyear.org
Sat Jun 9 18:44:15 CEST 2012


On Fri, Jun 8, 2012 at 3:34 PM, Yuval Greenfield <ubershmekel at gmail.com>
 wrote:

> > Loop statements may have an else clause; it is executed when the loop
> terminates through exhaustion of the list (with for) or when the condition
> becomes false (with while), but not when the loop is terminated by a break
> statement.


I don't think talking about exhaustion of the list is the simplest way to
think about this. Isn't it the distinction whether the loop exits at the
bottom or in the middle?

On Sat, Jun 9, 2012 at 12:46 AM, Arnaud Delobelle <arnodel at gmail.com> wrote:

> As Terry says, this is not the whole truth but you'd have to have a warped
> mind not to extrapolate the correct behaviour when there is a return or
> raise in the loop body.
>
>
If we can express this in a way that is the whole truth that's better. And
leaving out a very common scenario like return in a loop and an less common
one like raise. Asking readers of technical documentation to extrapolate
frequently leads to incorrect assumptions. Go read the docs on msdn if you
don't agree with that.

Here's my take:

Loop statements may have an else clause which is executed when the loop
exits normally (control flows off the bottom of the loop). If the loop
exits from the middle (through break, return, raise or something else),
then the else is not executed. It may help to think of the else as being
paired with an "if ... break" in the middle of the loop. If the break is
not executed then the else will be.


Likewise I would reword the comparison to try. In particular I would remove
the negative reference to if as I think that's misleading.

The else clause of a loop can also be thought of as similar to the else
clause of a try statement. A try statement’s else clause runs when no
exception, break or return occurs and the try exits normally, and a loop’s
else clause runs when no break or return occurs and the loop exits
normally. For more on the try statement and exceptions, see Handling
Exceptions.


Note that this corrects the error in the current docs which says "a try
statement’s else clause runs when no exception occurs" which is not true if
you exit the try via break or return.

--- Bruce
Follow me: http://www.twitter.com/Vroo http://www.vroospeak.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120609/778bc8b2/attachment.html>


More information about the Python-ideas mailing list