How to Break Multiple Loops in Python?

Python Tutorials

When loops such as ‘for’ and ‘while’ are nested, the break statement in the innermost loop breaks the execution only of the inner loop, while the outer loops continue to execute.

To break out of multiple loops in Python, you can use any of the following methods.

Use Return to Break Multiple Loops

Write code containing the nested loop inside a function block and use return instead of the break statement. This will cause the interpreter to exit out of all the loops.

def func():
    for x in range(10):
        for y in range(10):
            if y == 3:
                return
            print(y)
            
func()

Output:

0
1
2
3

Use Loop/Else Construct to Break Multiple Loops

Write each inner loop with an else block containing a continue statement, followed by a break at the end of the else block.

[outer for]    
    [inner for]
        [body]
    else:
        continue
    break

This else block will execute only if the inner loop terminates without calling break, which will skip the remaining of the loop (i.e. break statement).

If the inner loop breaks (i.e. [body]), then the else block will not execute, causing the break of all loops.

for y in range(5):
    for x in range(5):
        print(x)
        if x == 3:
            break
    else:
        continue
    break

Output:

0
1
2
3

Leave a Reply

Your email address will not be published. Required fields are marked *