Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - `break` out of all loops [duplicate]

People also ask

How do you break out of multiple loops in Python?

Another way of breaking out multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop.

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.

Does Break get out of all loops?

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break all while loops?

To break out of a while loop, you can use the endloop, continue, resume, or return statement.


You should put your loops inside a function and then return:

def myfunc():
    for i in range(1, 1001):
        for i2 in range(i, 1001):
            for i3 in range(i2, 1001):
                if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
                    print i*i2*i3
                    return # Exit the function (and stop all of the loops)
myfunc() # Call the function

Using return immediately exits the enclosing function. In the process, all of the loops will be stopped.


You can raise an exception

try:
    for a in range(5):
        for b in range(5):
            if a==b==3:
                raise StopIteration
            print b
except StopIteration: pass

why not use a generator expression:

def my_iterator()
    for i in range(1, 1001):
        for i2 in range(i, 1001):
            for i3 in range(i2, 1001):
                yield i,i2,i3

for i,i2,i3 in my_iterator():
    if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
        print i*i2*i3
        break

Not sure if this the cleanest way possible to do it but you could do a bool check at the top of every loop.

do_loop = True

for i in range(1, 1001):
    if not do_loop:
        break
    for i2 in range(i, 1001):
        # [Loop code here]
        # set do_loop to False to break parent loops