ChatGPT解决这个技术问题 Extra ChatGPT

How can I 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?

Why doesn't Python just have 'break(n)' where n is the number of levels you want to break out of.
C++ is nice here with goto if you're nestled deep in a lot of loops
Ned Batchelder has this interesting talk that addresses "How do I break out of two loops?". Spoiler alert: Make the double loop single.

R
Robert Rossney

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


This is another thought I had, since a get_input_yn() function would be useful elsewhere too, I'm sure.
agreed in this specific case, but in the general case of 'I have nested loops, what do I do' refactoring may not make sense.
Its usually possible to refactor the inner loop into its own method, that returns true to continue, false to break the outer loop. while condition1: / if not MyLoop2(params): break. An alternative is to set a boolean flag, that is tested at both levels. more = True / while condition1 and more: / while condition2 and more: / if stopCondition: more = False / break / ...
I agree that striving to use return is the right approach. And the reasoning is that, according to the Zen of Python, "flat is better than nested". We have three levels of nesting here and if that starts to get in the way, it is time to reduce the nesting or at least extract the whole nesting into a function of its own.
I know it may seem obvious, but an example using the original code would improve this answer.
C
Ciro Santilli Путлер Капут 六四事

Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.

for a in xrange(10):
    for b in xrange(20):
        if something(a, b):
            # Break the inner loop...
            break
    else:
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break

This uses the for / else construct explained at: Why does python use 'else' after for and while loops?

Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.

The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.


@RishitBansal Although this is a deep cut: The outer loop does matter because the inner break condition something(a, b) depends on a too. The outer loop may run as long as something(a, b) is not True.
Got this from a Raymond Hettinger video, youtu.be/OSGv2VnC0go?t=971, read "else" statements attached to for loops as "no_break", then it becomes easier to understand.
This is clever. :-) However, not straight-forward. Frankly, I am not convinced by arguments to keep labeled break or break(n) out of Python. The workarounds add more complexity.
This is very effective and efficient. Solves my question without any flaws!
This will not work in the following situation. If there are two breaks in the inner loop with one intended to break only inner loop while the other intended to break both loops
J
John Fouhy

PEP 3136 proposes labeled break/continue. Guido rejected it because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.


Although, refactor/return is usually the way to go, I've seen quite a few cases where a simple concise ‘break 2’ statement would just make so much sense. Also, refactor/return doesn't work the same for continue. In these cases, numeric break and continue would be easier to follow and less cluttered than refactoring to a tiny function, raising exceptions, or convoluted logic involving setting a flag to break at each nest level. It's a shame Guido rejected it.
break; break would be nice.
@Jeyekomon The problem is that you don't need 3 or more nested loops for this to be a problem. 2 nested loops are pretty common
"Code so complicated to require this feature is very rare". But if you ever do use code this complicated, the lack of labeled loops will make it even more complicated, as you must manually forward the break through all of the loops. Stupid.
Apparently, I can only edit a post for 5 minutes (it's been 6). So, here's my edited post: My 2 cents: Perl has labeled break (but calls it 'last') and 'next' to proceed directly to the next iteration. It is not at all rare - I use it all the time. I'm brand new to Python and already have a need for it. Also, numbered breaks would be horrible for refactoring - better to label the loop that you want to break out of, then use break
R
Russia Must Remove Putin

First, ordinary logic is helpful.

If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.

class GetOutOfLoop( Exception ):
    pass

try:
    done= False
    while not done:
        isok= False
        while not (done or isok):
            ok = get_input("Is this ok? (y/n)")
            if ok in ("y", "Y") or ok in ("n", "N") : 
                done= True # probably better
                raise GetOutOfLoop
        # other stuff
except GetOutOfLoop:
    pass

For this specific example, an exception may not be necessary.

On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.


Seriously, exceptions are extremely cheap and idiomatic python uses lots and lots of them. It's very easy to define and throw custom ones, as well.
Interesting idea. I'm torn as to whether to love it or hate it.
This solution would be more helpful, if it showed the two variations separately. (1) using a flag (done). (2) raising an exception. Merging them together into a single solution just makes it look complicated. For future readers: EITHER use all the lines involving done, OR define GetOutOfLoop(Exception) and raise/except that.
In general, using try-blocks for anything other then exceptions is very frowned upon. Try-blocks are specifically designed for error handling, and using them for some strange control flow is not very good, stylistically.
@tommy.carstensen That's nonsense; both defining a new exception subclass and raising it (as shown in the answer) and passing a custom message to the Exception constructor (e.g. raise Exception('bla bla bla')) are valid in both Python 2 and Python 3. The former is preferable in this case because we don't want our except block to catch all exceptions, but only the special exception we're using to exit the loop. If we do things the way you suggest, and then a bug in our code causes an unexpected exception to be raised, it'll be wrongly treated the same as deliberately exiting the loop.
M
Mark Dickinson

I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you really need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's with statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:

from contextlib import contextmanager
@contextmanager
def nested_break():
    class NestedBreakException(Exception):
        pass
    try:
        yield NestedBreakException
    except NestedBreakException:
        pass

Now you can use this context manager as follows:

with nested_break() as mylabel:
    while True:
        print "current state"
        while True:
            ok = raw_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": raise mylabel
            if ok == "n" or ok == "N": break
        print "more processing"

Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built Exception subclass for each use of nested_break; no need to declare your own Exception subclass each time.


k
krvolok

Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!


Simplest and easiest to read solution in my opinion. Thanks for sharing!
Although this is the easiest to apply, it becomes cumbersome when you have more than 2 loops you want to exit out of.
This is the [albeit hacky] solution that was being asked for. Thank you.
M
Matt J

First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the while loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...

You may also use goto in the following way (using an April Fools module from here):

#import the stuff
from goto import goto, label

while True:
    #snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y": goto .breakall
        if ok == "n" or ok == "N": break
    #do more processing with menus and stuff
label .breakall

I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.


If it is anything like the COME FROM command in INTERCAL, then nothing
i like the joke, but the point of stack overflow is to promote good code, so i have to vote you down :(
I think it's a clean and readable enough solution to qualify as good code, so I vote it up. :)
@J.T.Hurley no this is not clean and readable. I mean, it may look like it is clean and readable in this example but in any real life scenario goto's create a holy mess. (Also this is sooo anti-pythonic...)
goto gets a bad rep, any professional coder should be able to handle it properly in my opinion.
J
Justas

To break out of multiple nested loops, without refactoring into a function, make use of a "simulated goto statement" with the built-in StopIteration exception:

try:
    for outer in range(100):
        for inner in range(100):
            if break_early():
                raise StopIteration

except StopIteration: pass

See this discussion on the use of goto statements for breaking out of nested loops.


This looks much nicer than creating your own class to handle the exception, and looks very clean. Is there any reason I shouldn't do this?
In fact StopIteration is using for generators, but I think normally you don't have any uncatched StopIteration exception. So it seems like a good solution but there is not a mistake at creating new exception anyway.
Best and simplest solution for me
P
Peter Mortensen
keeplooping = True
while keeplooping:
    # Do stuff
    while keeplooping:
          # Do some other stuff
          if finisheddoingstuff():
              keeplooping = False

or something like that.

You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kind of like the GOTO method, provided you don't mind using an April Fool's joke module - it’s not Pythonic, but it does make sense.


this is sort of flag setting!
p
peterh

This isn't the prettiest way to do it, but in my opinion, it's the best way.

def loop():
    while True:
    #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": return
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff

I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.


This was the right solution for me. My use case was very different than the OP's. I was looping over essentially the same data twice to find permutations, so I didn't want to separate the two while loops.
P
Peter Mortensen

Keep looping if two conditions are true.

I think this is a more Pythonic way:

dejaVu = True

while dejaVu:
    while True:
        ok = raw_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y" or ok == "n" or ok == "N":
            dejaVu = False
            break

why not just while dejaVu:? You set it to true anyway.
hey that works! I was thinking in two True conditions to skip two loops, but just one is enough.
@MatthewScharley I think this is to show that this works in nested loops.
@MauroAspé this will not exactly do what the OP requests. it will still execute the whole outer loop but the target is that if you break the rest of the code will not get executed
@yamm Could that not be solved with a if not dejaVu: break at the bottom and thus exit the main loop? I think the solution is closest to what was asked. +1
M
Muhammad Faizan Fareed

There is no way to do this from a language level. Some languages have a goto others have a break that takes an argument, python does not. The best options are: Set a flag which is checked by the outer loop, or set the outer loops condition. Put the loop in a function and use return to break out of all the loops at once. Reformulate your logic.

Credit goes to Vivek Nagarajan, Programmer since 1987

Using Function

def doMywork(data):
    for i in data:
       for e in i:
         return 

Using flag

is_break = False
for i in data:
   if is_break:
      break # outer loop break
   for e in i:
      is_break = True
      break # inner loop break

M
Matt Billenstein

Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:

def it(rows, cols, images):
    i = 0
    for r in xrange(rows):
        for c in xrange(cols):
            if i >= len(images):
                return
            yield r, c, images[i]
            i += 1 

for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
    ... do something with r, c, image ...

This has the advantage of splitting up the complicated loop logic and the processing...


C
Community

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.


This does not seem to fulfill the requirement of double breaks. Works for the exact given problem, but not for the actual question.
@Dakkaron Are you sure you've understood the code correctly? The code does indeed solve the OPs question, and breaks similar to request. It does however not break out of multiple loops, but use the else clause to replace the need of doubling the break.
From my understanding the question was How to break out of multiple loops in Python? and the answer should have been "It does not work, try something else". I know it fixes the exact given example of the OP, but does not answer their question.
@Dakkaron, See the problem statement under the code, and in my opinion it does indeed answer the OPs question.
o
one_observation

An easy way to turn multiple loops into a single, breakable loop is to use numpy.ndindex

for i in range(n):
  for j in range(n):
    val = x[i, j]
    break # still inside the outer loop!

for i, j in np.ndindex(n, n):
  val = x[i, j]
  break # you left the only loop there was!

You do have to index into your objects, as opposed to being able to iterate through the values explicitly, but at least in simple cases it seems to be approximately 2-20 times simpler than most of the answers suggested.


L
Loax

In this case, as pointed out by others as well, functional decomposition is the way to go. Code in Python 3:

def user_confirms():
    while True:
        answer = input("Is this OK? (y/n) ").strip().lower()
        if answer in "yn":
            return answer == "y"

def main():
    while True:
        # do stuff
        if user_confirms():
            break

C
Community

Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the python reference

for i, j in ((i, j) for i in A for j in B):
    print(i , j)
    if (some_condition):
        break

You could scale it up to any number of levels for the loop

The downside is that you can no longer break only a single level. It's all or nothing.

Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on Python - `break` out of all loops but unfortunately that's closed as a duplicate of this one


It works for while loops too, you only need to write your generator as a def (with yield), not as a comprehension.
Yes, a speaker at a PyCon claims here that even @RobertRossney's accepted answer is not truly Pythonic, but a generator is the right way to break multiple loops. (I'd recommend watching the whole video!)
u
user

I'd like to remind you that functions in Python can be created right in the middle of the code and can access the surrounding variables transparently for reading and with nonlocal or global declaration for writing.

So you can use a function as a "breakable control structure", defining a place you want to return to:

def is_prime(number):

    foo = bar = number

    def return_here():
        nonlocal foo, bar
        init_bar = bar
        while foo > 0:
            bar = init_bar
            while bar >= foo:
                if foo*bar == number:
                    return
                bar -= 1
            foo -= 1

    return_here()

    if foo == 1:
        print(number, 'is prime')
    else:
        print(number, '=', bar, '*', foo)

>>> is_prime(67)
67 is prime
>>> is_prime(117)
117 = 13 * 9
>>> is_prime(16)
16 = 4 * 4

R
Rafiq

By using a function:

def myloop():
    for i in range(1,6,1):  # 1st loop
        print('i:',i)
        for j in range(1,11,2):  # 2nd loop
            print('   i, j:' ,i, j)
            for k in range(1,21,4):  # 3rd loop
                print('      i,j,k:', i,j,k)
                if i%3==0 and j%3==0 and k%3==0:
                    return  # getting out of all loops

myloop()

Try running the above codes by commenting out the return as well.

Without using any function:

done = False
for i in range(1,6,1):  # 1st loop
    print('i:', i)
    for j in range(1,11,2):  # 2nd loop
        print('   i, j:' ,i, j)
        for k in range(1,21,4):  # 3rd loop
            print('      i,j,k:', i,j,k)
            if i%3==0 and j%3==0 and k%3==0:
                done = True
                break  # breaking from 3rd loop
        if done: break # breaking from 2nd loop
    if done: break     # breaking from 1st loop

Now, run the above codes as is first and then try running by commenting out each line containing break one at a time from the bottom.


M
MichaelChirico

Try using an infinite generator.

from itertools import repeat
inputs = (get_input("Is this ok? (y/n)") for _ in repeat(None))
response = (i.lower()=="y" for i in inputs if i.lower() in ("y", "n"))

while True:
    #snip: print out current state
    if next(response):
        break
    #do more processing with menus and stuff

R
RufusVS
# this version uses a level counter to choose how far to break out

break_levels = 0
while True:
    # snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y":
            break_levels = 1        # how far nested, excluding this break
            break
        if ok == "n" or ok == "N":
            break                   # normal break
    if break_levels:
        break_levels -= 1
        break                       # pop another level
if break_levels:
    break_levels -= 1
    break

# ...and so on

R
RufusVS
# this version breaks up to a certain label

break_label = None
while True:
    # snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y":
            break_label = "outer"   # specify label to break to
            break
        if ok == "n" or ok == "N":
            break
    if break_label:
        if break_label != "inner":
            break                   # propagate up
        break_label = None          # we have arrived!
if break_label:
    if break_label != "outer":
        break                       # propagate up
    break_label = None              # we have arrived!

#do more processing with menus and stuff

F
Fateh

Here's an implementation that seems to work:

break_ = False
for i in range(10):
    if break_:
        break
    for j in range(10):
        if j == 3:
            break_ = True
            break
        else:
            print(i, j)

The only draw back is that you have to define break_ before the loops.


k
kcEmenike

What I would personally do is use a boolean that toggles when I am ready to break out the outer loop. For example

while True:
    #snip: print out current state
    quit = False
    while True:
        ok = input("Is this ok? (y/n)")
        if ok.lower() == "y":
            quit = True
            break # this should work now :-)
        if ok.lower() == "n":
            quit = True
            break # This should work too :-)
    if quit:
        break
    #do more processing with menus and stuff

S
Skycc

probably little trick like below will do if not prefer to refactorial into function

added 1 break_level variable to control the while loop condition

break_level = 0
# while break_level < 3: # if we have another level of nested loop here
while break_level < 2:
    #snip: print out current state
    while break_level < 1:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y": break_level = 2 # break 2 level
        if ok == "n" or ok == "N": break_level = 1 # break 1 level

h
helmsdeep

You can define a variable( for example break_statement ), then change it to a different value when two-break condition occurs and use it in if statement to break from second loop also.

while True:
    break_statement=0
    while True:
        ok = raw_input("Is this ok? (y/n)")
        if ok == "n" or ok == "N": 
            break
        if ok == "y" or ok == "Y": 
            break_statement=1
            break
    if break_statement==1:
        break

Good point, however in each of levels above our inner level of interest we would need to scan that variable. Feels really bad that the language does not have a GoTo instruction, performance-wise.
N
Nathan Garabedian

My reason for coming here is that i had an outer loop and an inner loop like so:

for x in array:
  for y in dont_use_these_values:
    if x.value==y:
      array.remove(x)  # fixed, was array.pop(x) in my original answer
      continue

  do some other stuff with x

As you can see, it won't actually go to the next x, but will go to the next y instead.

what i found to solve this simply was to run through the array twice instead:

for x in array:
  for y in dont_use_these_values:
    if x.value==y:
      array.remove(x)  # fixed, was array.pop(x) in my original answer
      continue

for x in array:
  do some other stuff with x

I know this was a specific case of OP's question, but I am posting it in the hope that it will help someone think about their problem differently while keeping things simple.


This is probably not Python. What is the type of array? Probably list, but what does it contain? Even if it contains ints, array.pop(x) will probably not do what you want.
That's a good point. I can't find the code that I referenced. For anyone reading this, array.pop(i) "Removes the item with the index i from the array and returns it." as per python documentation. So one would need to get the index of item x in the array to make this code work as expected. There is also the array.remove(x) function which would do what is expected. I will modify my answer above to fix that error. This assumes the second array contains no duplicates, as array.remove(x) will only remove the first instance of x found.
Ok, then I get it. In that case, simply using break instead of continue would do what you want, wouldn't it? :-)
Yeah, for efficiency and clarity, you'd probably want to use break instead of continue in these examples. :)
P
Peter Mortensen

Solutions in two ways

With an example: Are these two matrices equal/same? matrix1 and matrix2 are the same size, n, two-dimensional matrices.

First solution, without a function

same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)

for i in range(n):
    for j in range(n):

        if matrix1[i][j] != matrix2[i][j]:
            same_matrices = False
            inner_loop_broken_once = True
            break

    if inner_loop_broken_once:
        break

Second solution, with a function

This is the final solution for my case.

def are_two_matrices_the_same (matrix1, matrix2):
    n = len(matrix1)
    for i in range(n):
        for j in range(n):
            if matrix1[i][j] != matrix2[i][j]:
                return False
    return True

t
thanos.a

Trying to minimal changes to the OP's question, I just added a flag before breaking the 1st for loop and check that flag on the outer loop to see if we need to brake once again.

break_2 = False
while True:
    # Snip: print out current state
    if break_2: break
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break_2 = True
        if break_2: break
        if ok.lower() == "n": break
    # Do more processing with menus and stuff

Can you describe what you changed? What is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
C
Charlie Clark

I came across this recently and, wanting to avoid a duplicate return statement, which can conceal logical errors, looked at @yak's idea. This works well within nested for loops but is not very elegant. An alternative is to check for the condition before the next loop:

b = None
for a in range(10):
    if something(a, b): # should never = True if b is None
        break
    for b in range(20):
        pass

This might not work everywhere but is adaptable and, if required, has the advantage of allowing the condition to be duplicated rather than a potential result.