Nested loops are commonly used in Python to carry out repeated actions on multidimensional data, such as matrices.
However, there might be situations where one would want to exit from multiple loops at once given a certain condition, and Python doesn’t come with a straightforward mechanism to break out, like the break
statement or regular loops. This tutorial will demonstrate some techniques to exit from a nested loop in Python.
1. Using Exceptions
One way to exit a nested loop is by using exceptions. Here’s how you can use exceptions to break out of nested loops:
- Define a custom exception class that inherits from the base
Exception
class. - Inside the nested loop, raise the custom exception when the desired condition is met.
- Enclose the nested loop inside a
try
block and handle the custom exception using anexcept
block.
For example, consider the following nested loop:
1 2 3 4 5 |
for i in range(10): for j in range(10): print(i, j) if i == 5 and j == 5: break |
To break out of both loops when i == 5
and j == 5
, use the following approach:
1 2 3 4 5 6 7 8 9 10 11 |
class BreakNestedLoop(Exception): pass try: for i in range(10): for j in range(10): print(i, j) if i == 5 and j == 5: raise BreakNestedLoop except BreakNestedLoop: pass |
2. Using Functions
Another approach to exit a nested loop is by wrapping the nested loop in a function and using the return
statement. Here’s the process:
- Create a function that contains the nested loop.
- Inside the nested loop, call the
return
statement when the desired condition is met. - Invoke the function in your code.
Using the same example as before, you can break out of both loops with the following code:
1 2 3 4 5 6 7 8 |
def nested_loop(): for i in range(10): for j in range(10): print(i, j) if i == 5 and j == 5: return nested_loop() |
Full Code and Output
Exception Method:
1 2 3 4 5 6 7 8 9 10 11 |
class BreakNestedLoop(Exception): pass try: for i in range(10): for j in range(10): print(i, j) if i == 5 and j == 5: raise BreakNestedLoop except BreakNestedLoop: pass |
Output:
0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 ... 5 5
Function Method:
1 2 3 4 5 6 7 8 |
def nested_loop(): for i in range(10): for j in range(10): print(i, j) if i == 5 and j == 5: return nested_loop() |
Output:
0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 ... 5 5
Conclusion
In this tutorial, we have explored two methods to break out nested loops in Python using exceptions and functions.
While the exception method provides a more “Pythonic” approach, the function method can be easier to read and understand for those who are new to Python. Choose the method that works best for your specific use case and coding style.