Skip to content

Break in nested loops Python | Example code

  • by

To break out of nested (multiple) loops you need to use a variable to keep track of whether you’re trying to exit and check it each time the parent loop occurs.

Example Break in nested loops Python

Simple example code.

is_looping = True

for i in range(5):  # outer loop
    for x in range(4):  # inner loop
        if x == 2:
            is_looping = False
            print("Inner Loop Break", x)
            break  # break out of the inner loop

    if not is_looping:
        print("Outer Loop Break", i)
        break  # break out of outer loop


Break in nested loops Python

Another example

for i in range(3):
    print("Outer loop:", i)
    for j in range(3):
        print("Inner loop:", j)
        if j == 1:
            break  # Breaks out of the inner loop

In this example, the inner loop is terminated when the value of j is equal to 1. As a result, it breaks out of the inner loop and continues with the next iteration of the outer loop.

Note: the break statement only exits the innermost loop it is placed in. You may need additional statements to break out of the desired loop if you have multiple nested loops.

Comment if you have any doubts or suggestions on this Python nested loop program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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