In this tutorial, we will learn how to break out of multiple loops and to do this there are two methods for breaking out of multiple loops and they are using a Flag Variable and Exceptions.
Using a Flag Variable:
This method uses a Boolean flag variable to control the loop termination.
- Flag Initialization: At the beginning of the outer loop, initialize the flag variable to ” False “.
- Flag Usage: Within the nested loops, whenever want to break out of all loops, set the flag to ” True “.
- Condition Check: Before each loop iteration, check the flag variable . If it’s” Ture “, break out of the outer loop using ” break “.
Example: In the provided example below, flag is initially set to False. Inside the inner loop, if j equals 3, flag is set to True, causing the outer loop to break.
flag = False for i in range(5): if flag: break for j in range(5): if j == 3: flag = True break print(i, j)
Output:
0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 3 0 3 1 3 2 4 0 4 1 4 2
This output demonstrates the iterations of the nested loops until the condition ‘ j == 3 ‘ is met in the inner loop. Once ‘ j ‘ reaches ‘ 3 ‘, the outer loop breaks due to the flag being set to ‘ True ‘, and the execution stops.
Using Exceptions:
This method uses custom exceptions to break out of nested loops.
- Exception Definition: Define a custom exception class, such as “ BreakLoop “.
- Loop Execution: Within the loops, whenever want to break out, raise the custom exception.
- Exception Handling: The outer loop is wrapped in a ” try-except ” block. When the custom exception is raised, the execution jumps to the ” except ” block.
Example: In the provided example below, when j equals 3, the BreakLoop exception is raised, causing the execution to jump out of the nested loops.
class BreakLoop(Exception): pass try: for i in range(5): for j in range(5): if j == 3: raise BreakLoop print(i, j) except BreakLoop: pass
Output: Here the output is same for both the codes because both methods achieve the same result of breaking out the loops when ‘ j == 3 ‘ is met in the inner loop. Once the ‘ BreakLoop ‘ exception is raised, the execution jumps to the ‘ except ‘ block, effectively terminating the nested loops.
Both methods offer a way to break out of multiple loops in python, proving flexibility based on your coding preferences and specific requirements.