The break statement in Python is used to exit or “break” a loop (for or while) prematurely. When the break statement is encountered, the program’s control flow immediately exits the loop, and the program continues with the statements that follow the loop.
Here are three examples illustrating the use of break:
Breaking a for loop:
Example to use break on for-loop in python
for i in range(10):
if i == 5:
break
print(i)
Output
0
1
2
3
4
In this example, the for loop is supposed to iterate from 0 to 9. However, when i equals 5, the break statement is executed, and the loop is terminated. So, the output will be numbers from 0 to 4.
Exiting a while loop:
Example to use break on while loop in python
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
Output
0
1
2
3
4
In this example, the while loop would run indefinitely because its condition is True. However, the break statement allows us to exit the loop when count is greater than or equal to 5. So, the output will be numbers from 0 to 4.
Breaking out of nested loops:
Using break in nested loops
for i in range(1, 4):
for j in range(1, 4):
if i == j == 2:
break
print(f"i = {i}, j = {j}")
if i == j == 2:
break
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
In this example, we have two nested for loops. The break statement will only exit the inner loop when i and j are both 2. To exit both loops, we need another break in the outer loop. The output will be pairs of i and j values until both are equal to 2.
Remember, use the break statement wisely, as it can make your code more efficient but also more complex. It’s best used when you need to exit a loop based on a certain condition being met.