Matthew Scharley Matthew Scharley - 1 year ago 171
Python Question

How to break out of multiple loops in Python?

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)")
if ok == "y" or ok == "Y": break 2 #this doesn't work :(
if ok == "n" or ok == "N": break
#do more processing with menus and stuff

Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?

Edit-FYI: get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns

Answer Source

My first instinct would be to refactor the nested loop into a function and use return to break out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download