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

Rob Cliffe rob.cliffe at btinternet.com
Fri Jun 8 11:44:55 CEST 2012


On 08/06/2012 10:04, 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. I think a better scheme would be to have more meaningful keywords or keyword-combinations, e.g.

for x in iterable: # do stuff ifempty: # or perhaps ifnoiter: (also applicable to while loops) # do stuff #ifbreak: # do stuff #ifnobreak: # do stuff

which would give all the flexibility while making it reasonably clear what was happening. Rob Cliffe



More information about the Python-ideas mailing list