How to Break Out of Two Nested While Loops in Python

In Python, a while loop is used to execute a block of code or statement multiple times until the condition becomes false.

The control structure allows developers to repeat a specific code block until the condition maintained in the while loop remains true. However, there might be situations where you need to terminate a loop prematurely or break out of nested loops.

To help with that, Python provides a ‘break’ statement. This guide will provide a step-by-step look at how to break out of two nested while loops in Python.

Step 1: Understand the ‘break’ statement

In Python, the break statement enables you to control the flow of your program. It allows you to exit from a loop when an external condition is triggered. The break statement is used within an if statement and once the condition is satisfied, the loop will be terminated immediately, and the control is transferred to the next statement after the loop.

Step 2: Implement a nested while loop

A nested loop is a loop inside another loop. The inner or second while loop will always run completely on every iteration of the outer or first while loop. Here is an example:

Step 3: Use the ‘break’ statement in the nested while loop

To break out from the nested loops, you can use a break statement which will terminate the innermost loop and resume execution at the next line. If you want to break out of both loops at the same time, you can use a break statement in both loops as shown:

Note: This would only break one level out of the loops. In the above code, if the outer_counter is 1 then control will come out of both loops.

Outer 0 Inner 0
Outer 0 Inner 1
Outer 1 Inner 0
Outer 1 Inner 1

Conclusion

In a nutshell, this tutorial helped you comprehend how to exit two nested while loops in Python using the ‘break’ statement. This technique is a great way to manage your iterations in a more flexible manner, allowing you to control your program’s flow effectively based on specific conditions. Happy coding!