Let's say you have some nested for
-loop that you want to break out of from the inner loop:
x = default
for key, values in dict_of_sets:
for value in values:
if predicate(value):
x = key
break 2 # INVALID SYNTAX, SADLY...
Well, it turns out that Python supports for-else
, so this can be made trivial:
x = default_value
for key, values in dict_of_sets:
for value in values:
if predicate(key, value):
x = value
break # THIS BREAKS BOTH LOOPS!
else:
continue
break
You don't need to know why this works to use it; but, if you do, here's how it works:
- When the inner
for
-loop exhausts, itselse
-clause executes next, whichcontinue
s the program through that iteration of the outerfor
-loop (quietly skipping thebreak
statement on line 9). - If the inner
for
-loop is, instead, killed with thebreak
on line 6, itselse
-clause is skipped, allowing thebreak
statement on line 9 to execute and terminate the outerfor
-loop.
This can be used as much as you like:
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
for m in range(3):
for n in range(3):
print(i, j, k, l, m, n)
if input("Press enter to continue, or type anything to break out of all these loops.\n> "):
break # THIS WILL BREAK ALL OF THE LOOPS!
else:
continue
break
else:
continue
break
else:
continue
break
else:
continue
break
else:
continue
break