In this tutorial, we will discuss the usage of the “break” keyword in Python. The Python break statement is a loop control statement that terminates the loop statement, irrespective of whether the loop has completed all its iterations or not. It can be used in while and for loops.
Step 1: Using break in a while loop
Let’s start by using the break statement in a while loop. The break statement will terminate the loop as soon as it encounters a specific condition.
1 2 3 4 5 6 |
i = 1 while i < 10: print(i) if i == 5: break i += 1 |
In the code above, the while loop will break as soon as i is equal to 5, and thus, the numbers from 1 to 5 will be printed.
Step 2: Using break in a for loop
The break statement can also be used in for loops. The following example demonstrates this:
1 2 3 4 |
for i in range(1, 10): if i == 5: break print(i) |
In the code above, the for loop breaks when i equals 5, so the numbers from 1 to 4 are printed.
Step 3: Using break in nested loops
The break statement also works in nested loops. When a break statement is encountered in the inner loop, it terminates only the inner loop, not the entire loop structure. Here is an example:
1 2 3 4 5 6 7 |
for i in range(1, 6): for j in range(1, 6): if j == 3: break print(j) print('Finished inner loop') print('Finished all loops') |
In the code above, the inner loop breaks when j reaches 3. However, the outer loop continues to run until i reaches 5.
Conclusion
Recognizing when and how to use the break statement in Python optimizes both your coding process and program flow control. It’s a powerful tool that allows loops to become more flexible to specific conditions. Knowing this, keep practicing with different Python loops and mastering the conditions for the break statement.