[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Fri Oct 2 13:01:20 CEST 2009

Yuvgoog Greenle wrote:
> 1. Not allowing a for loop that has no "break" to have an "else". Just
> like "else" isn't allowed when there isn't an "except" in the "try".
> There really is no excuse, justification or sense in a "for" loop that
> has no "break" yet has an "else".

As Stephen said, that's a very good point. Having the compiler issue a
SyntaxWarning when compiling such code is perfectly possible and would
make a great deal of sense (and probably prevent many cases of naive

> 2. Lets not talk about removing the "else" from for/while completely
> since it does have its fans and cute use cases.

Good :)

> 3. Renaming this construct for py4k wouldn't be too crazy if you use the
> existing reserved words "not" and "break". Look at this code and please
> note that it doesn't need any comments to make it readable (as opposed
> to Nick's example, no offence):
> for item in list_of_stuff:
>     if item.is_awesome():
>         break
> not break:
>     print("nothing is awesome :(")

If you want to turn the "else" into something explicit, the phrase
you're looking for would be "elif not break". I think it's better just
to teach people that's what the "else" means though - no need to make
them type it every time.

If you want to do things in the break case then that code goes inside
the body of the loop (after checking the break condition, but before the
break statement itself).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list