Home > Article > Backend Development > How to Escape Nested Loops in Python Without Exceptions?
Escaping Nested Loops without Exceptions
While using exceptions to break out of nested loops is possible, it can be cumbersome. Fortunately, there are cleaner approaches available in Python.
Using the "break" and "continue" Statements
A more elegant solution involves using the break and continue statements. The break statement immediately exits the innermost loop, while continue continues to the next iteration within the current loop.
Consider the following nested loop:
<code class="python">for x in range(10): for y in range(10): print(x * y) if x * y > 50: break else: continue # Only executed if the inner loop did NOT break break # Only executed if the inner loop DID break</code>
In this example, the break statement within the inner loop allows us to exit both loops when the condition x * y > 50 is met. The else clause after the inner loop checks if the inner loop terminated normally (without encountering a break). If so, it executes the continue statement to proceed to the next iteration of the outer loop.
Example with Multiple Nested Loops
This technique can be extended to deeper loops as well:
<code class="python">for x in range(10): for y in range(10): for z in range(10): print(x, y, z) if (x * y * z) == 30: break else: continue break else: continue break</code>
This code demonstrates how to break out of all three nested loops when the condition (x * y * z) == 30 is satisfied. The else and continue statements ensure that the outer loops are traversed correctly based on the termination status of the inner loops.
The above is the detailed content of How to Escape Nested Loops in Python Without Exceptions?. For more information, please follow other related articles on the PHP Chinese website!