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

Terry Reedy tjreedy at udel.edu
Sat Jun 9 02:15:27 CEST 2012


On 6/8/2012 6:34 PM, Yuval Greenfield wrote:

>  > Loop statements may have an else clause; it is executed immediately
> after the loop but is skipped if the loop was terminated by a break
> statement.

As I said in my reply on pydev, that is misleading. The else clause 
executes if and when the loop condition is false. Period. Simple rule.

It will not execute if the loop is exited by break OR if the loop is 
exited by return OR if the loop is exited by raise OR if the loop never 
exits. (OR is the loop is aborted by external factors.) As far as else 
is concerned, there is nothing special about break exits compared to 
return or raise exits.

But Nick's doc addition and your alternative imply otherwise. One could 
read Nick's statement and your paraphrase as suggesting that the else 
will by executed if the loop is exited by return (like the finally of 
try) or raise (like the except of try). And that is wrong.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list