[Python-ideas] for/else syntax

Yuvgoog Greenle ubershmekel at gmail.com
Sat Oct 3 15:30:55 CEST 2009

It just hit me. The for...else is so cryptic because of one big issue
- the "else".

Consider the following code:

for obj in iterable:
    if found_it(obj):
        # Found what we were looking for!
if not break:
    # It wasn't there :(

Similarly for while loops:

while self.more_points_to_check():
    if self.found_it():
        # Found the desired point
if not break:
    # Exhausted the search space :(

Notice how readable and beautiful the code has become. We have 2
implementation options:
1. an "if" that comes immediately after a for/while can have the
special keywords "not" or "break".
2. the for/while syntax has an optional "if break" or "if not break".

I'd like to hear if people like this idea and if so, which of the 2
options do you like better.

Check it out, there's no need for a syntax error because it's so
obviously wrong:

for item in list_of_items:
if not break:

Also, now that the syntax is generic, you can add on to it whatever
you like. For example:

for item in list_of_items:
    if item.is_gold():
    if item.is_silver():
if break and searching_for_metals:


More information about the Python-ideas mailing list