I went a long time before ever using an else: clause in a python for
loop, mainly because I just never needed it. Then one day
it hit me that it was perfect for what I needed to do. The idea is that
code in the else: clause is only executed if we don't encounter a break
statement in the body of the for loop. See The for
statement in the Python documentation for details.
Here's an example of how I've recently used the for loop's else: clause.
YUCKY_STUFF = [
'sugar',
'wheat',
'high fructose corn syrup',
'soybean',
'peanut',
]
for food in foods:
for ingredient in YUCKY_STUFF:
if food.find(ingredient) != -1:
break
else:
consume(food)
The code above shows a way to exclude certain unwanted items from a
sequence. In this case we skip a food if it contains any of the things
defined in the YUCKY_STUFF list. Those that aren't excluded are
consume()'d.
This "exclude if any condition is true" pattern seems like a very natural
way to use a for loop's else clause.
Take care. |