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

Do comment if you have any doubts and 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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.