Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of multiple loops?

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.lower() == "y": break 2 #this doesn't work :(         if ok.lower() == "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?

like image 278
Matthew Scharley Avatar asked Oct 10 '08 00:10

Matthew Scharley


People also ask

How do you break out of a loop in a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How do you avoid many for loops?

Originally Answered: How can I avoid nested "for loop" for optimize my code? Sort the array first. Then run once over it and count consecutive elements. For each count larger than 1, compute count-choose-2 and sum them up.

Does break in python break out of all loops?

When break is executed in the inner loop, it only exits from the inner loop and the outer loop continues.


1 Answers

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

like image 116
Robert Rossney Avatar answered Oct 07 '22 03:10

Robert Rossney