Given the following code (that doesn\'t work):
while True:
#snip: print out current state
while True:
ok = get_input(\"Is this ok? (y/n)\")
There is a hidden trick in the Python while ... else
structure which can be used to simulate the double break without much code changes/additions. In essence if the while
condition is false, the else
block is triggered. Neither exceptions, continue
or break
trigger the else
block. For more information see answers to "Else clause on Python while statement", or Python doc on while (v2.7).
while True:
#snip: print out current state
ok = ""
while ok != "y" and ok != "n":
ok = get_input("Is this ok? (y/n)")
if ok == "n" or ok == "N":
break # Breaks out of inner loop, skipping else
else:
break # Breaks out of outer loop
#do more processing with menus and stuff
The only downside is that you need to move the double breaking condition into the while
condition (or add a flag variable). Variations of this exists also for the for
loop, where the else
block is triggered after loop completion.