Python break statement
Created By: chatGPT
The break statement in Python is used to exit a loop prematurely. When break is executed inside a loop, the loop is terminated and control is transferred to the next statement following the loop. This can be particularly useful when a specific condition is met, or when you want to exit a loop based on certain criteria.
for i in range(10):
if i == 5:
break
print(i) # This will print numbers 0 to 4
In the example above, the loop runs from 0 to 9. As soon as the value of i reaches 5, the break statement is triggered, and the loop is exited. Therefore, the printed output will only include the numbers from 0 to 4.
Output:
0
1
2
3
4
You can also use break within nested loops. In such cases, it will only terminate the innermost loop where it is called. Here's an example that showcases this functionality.
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j) # This will print (i, j) pairs until j is 1
In this nested loop example, for every iteration of the outer loop (controlled by i), the inner loop (controlled by j) will stop executing when j equals 1. Thus, you'll only see pairs where j is 0.
Output:
0 0
1 0
2 0
It's important to note that the break statement can also be used in other types of loops like while loops. The principle remains the same: once the break is hit, the loop halts and control moves to the next line of code after the loop.
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break # Exits the loop when count reaches 3
In this while loop, the output will display values 0, 1, and then stop when count equals 3 due to the break statement. This demonstrates yet another use case for controlling loop execution.
Output:
0
1
2