How to Continue an Outer Loop in Python?

Estimated read time 2 min read

To continue an outer loop in Python, you can use the continue statement within the inner loop to skip the remaining iterations of the inner loop and continue with the next iteration of the outer loop. Here’s an example:

for outer in range(1, 4):
    print("Outer loop iteration:", outer)
    for inner in range(1, 4):
        print("Inner loop iteration:", inner)
        if inner == 2:
            continue  # Continue the outer loop

print("Done")

In this example, we have an outer loop that iterates from 1 to 3, and an inner loop that also iterates from 1 to 3. The continue statement is used within the inner loop to skip the remaining iterations of the inner loop when the condition inner == 2 is met.

When inner is equal to 2, the continue statement is executed, causing the program to skip the remaining iterations of the inner loop and move to the next iteration of the outer loop. This allows the outer loop to continue executing with the next value.

The output of this example will be:

Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Done

As you can see, when the inner loop reaches an iteration where inner == 2, it immediately continues with the next iteration of the outer loop.

By using the continue statement within the inner loop, you can control the flow of execution and skip specific iterations of the outer loop when necessary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply