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

Ned Batchelder ned at nedbatchelder.com
Fri Jun 8 15:13:56 CEST 2012

```Just to add another attempt at explaining the for/else confusion, the
analogy that keeps it straight in my mind is that the "else" is really
paired with the "if .. break" inside the loop:
http://nedbatchelder.com/blog/201110/forelse.html

--Ned.

On 6/8/2012 5:04 AM, Nick Coghlan wrote:
> (context for python-ideas: my recently checked in changes to the
> tutorial, that added the final paragraph to
> http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
>
> On Fri, Jun 8, 2012 at 5:29 PM, Stephen J. Turnbull<stephen at xemacs.org>  wrote:
>> Note: reply-to set to python-ideas.
>>
>> Nick Coghlan writes:
>>
>>   >  The inaccuracies in the analogy are why this is in the tutorial, not the
>>   >  language reference. All 3 else clauses are really their own thing.
>>
>> Nick, for the purpose of the tutorial, actually there are 4 else
>> clauses: you need to distinguish *while* from *for*.  It was much
>> easier for me to get confused about *for*.
> The only thing I'm trying to do with the tutorial update is to
> encourage beginners to be start thinking in terms of try/except/else
> when they first encounter for/break/else and while/break/else. That's
> it.
>
> Yes, ultimately once people fully understand how it works under the
> hood (including the loop-and-a-half construct for infinite while
> loops), they'll release it's actually closely related to conditionals
> as well, but anyone that places too much weight on the following
> obvious parallel is going to be confused for a long time. After all:
>
>    if iterable:
>      ...
>    else:
>      ...
>
> is *very* similar in appearance to:
>
>    for x in iterable:
>      ...
>    else:
>      ...
>
> I believe that parallel is 99% of the reason why people get confused
> about the meaning of the latter.
>
> The point of the tutorial update is to give readers a slight nudge
> towards thinking of the latter as:
>
>    for x in iterable:
>      ...
>    except break:  # Implicit in the semantics of loops
>      pass
>    else:
>      ...
>
> Would it be worth adding the "except break:" clause to the language
> just to make it crystal clear what is actually going on? I don't think
> so, but it's still a handy way to explain the semantics while gently
> steering people away from linking for/else and if/else too closely. I
> actually agree all of the else clauses really *are* quite closely
> related (hence the consistent use of the same keyword), but the
> relationship is *not* the intuitively obvious one that comes to mind
> when you just look at the similarity in the concrete syntax
> specifically of for/else and if/else.
>
> Cheers,
> Nick.
>

```