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

Steven D'Aprano steve at pearwood.info
Sat Jun 9 19:48:28 CEST 2012

```Bruce Leban wrote:
> 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?

[Aside: I believe that isn't Yuval's description above. As I understand it, he
is quoting the current docs.]

Loops exit at the top, not the bottom. This is most obvious when you think
about a while loop:

while condition:
...

Of course you have to be at the top of the loop for the while to check
condition, not the bottom. For-loops are not quite so obvious, but execution
has to return back to the top of the loop in order to check whether or not the
sequence is exhausted.

Whether or not it is the *simplest* way to think about for/else, talking about
exhaustion of the list (iterable) is correct.

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

Should we ask readers to extrapolate what happens when the for loop variable
is a keyword (e.g. "for None in sequence"), or explicitly mention what happens?

Should we ask readers to extrapolate what happens when the for loop sequence
doesn't actually exist, or explicitly tell them that they get a NameError and
the loop doesn't run? Should we do this for every single function?

Frankly, you cannot avoid asking readers to extrapolate, because there is an
infinite number of things that they could do, and you cannot possibly document
them all.

--
Steven

```