[Python-ideas] for/else syntax

Jared Grubb jared.grubb at gmail.com
Sat Oct 3 08:15:53 CEST 2009

On 2 Oct 2009, at 20:43, Yuvgoog Greenle wrote:
> Ask a person who knows python the following questions:
> Question #1: Do you know what happens when an "else" appears after a  
> "for" loop?
>    if they answer yes then say never mind.
>    otherwise: continue to question #2.
> Question #2: When does the code in the "else" block execute? Of course
> you don't know so it's ok to guess.
>    If they answer "when a break didn't occur", I'm willing to give
> you, the asker, up to 100 lines of patch code in whatever python
> project you want.
>    If they answer "only when the for loop didn't run or was an empty
> list" then you don't owe me anything.

And then ask those same people if they know what a "data descriptor"  
is. There's some features of a language you just have to learn. And  
frankly, the for/else statement is very simple. It's surprising the  
first time you see it, but that's because few other languages have it.  
But, once you learn it, it's VERY handy.

On 2 Oct 2009, at 22:08, Nick Coghlan wrote:
> After the additional posts in the discussion, I'm back to my previous
> opinion - the construct should be referred to as break/else (or
> for/break/else and while/break/else) and we should at least  
> investigate
> having the compiler itself raise at least a SyntaxWarning if it
> encounters a for/else or while/else construct without also  
> encountering
> a break statement inside the loop.

I would disagree. Imagine, while trying to debug code, you comment out  
an if statement inside the for loop, and now suddenly the whole loop  
becomes syntactically invalid. Plus, it's not only a break that could  
potentially make a for/else a valid construct. Return and yield are  
both legitimate, and technically anything that can throw an exception  
is too. Trying to implement the lexer to scan for all the possible  
combinations does not seem to be worth the effort.


More information about the Python-ideas mailing list