Course contentsShow
← Python
Lesson 107 of 1,0602. Control Flow and LogicFree lesson

Controlling Nested Loop Exits

Learners will develop strategies to break out of multiple nested loops simultaneously using flag variables or function returns.

In this lesson, you will learn how to break out of multiple layers of nested loops at once when a specific condition is met.

The Nested Loop Challenge

When you nest loops, a break statement only exits the innermost loop. If you are searching through a multi-dimensional structure—like a grid of numbers—and find your target, the outer loop will continue to run unless you take extra steps.

Strategy 1: Using Flag Variables

A common way to stop everything is to introduce a "flag." This is a boolean variable that tracks whether we have finished our task. We set the flag to True when we find what we need, and the outer loop checks that flag to see if it should also break.

found = False
for i in range(5):
    for j in range(5):
        if i == 2 and j == 2:
            print("Target found!")
            found = True
            break  # Exits the inner loop
    if found:
        break  # Exits the outer loop

Strategy 2: Returning from Functions

A cleaner, more professional approach is to wrap your nested loops inside a function. In Python, the return statement immediately exits the entire function, regardless of how many loops you are currently inside.

def find_target():
    for i in range(5):
        for j in range(5):
            if i == 2 and j == 2:
                return "Target found!" # Exits the loops AND the function
    return "Not found"

result = find_target()
print(result)

Why This Matters

Using a flag or a function return prevents your program from wasting time iterating through unnecessary elements once the desired outcome has been achieved. It keeps your code efficient and prevents logical errors where the outer loop might continue processing data you no longer need. While flags are great for simple scripts, encapsulating logic in functions is generally the preferred approach for readability.

Key Takeaway: Use flag variables or function returns to break out of nested loops simultaneously, as a standard break only exits the innermost loop.