The break statement is a keyword in Python that is used to terminate the execution of a loop prematurely. When a break statement is encountered inside a loop, the loop is immediately exited, and the control flow moves to the next line of code following the loop. This is particularly useful when you want to stop the loop based on a certain condition, even if the loop hasn’t finished iterating over all items.
The break statement is often used in scenarios where you need to exit a loop early, such as when a specific condition is met. It is also commonly used within nested loops to exit the innermost loop first and then proceed to outer loops.
# Loop statements
break
In this example, the loop will terminate as soon as the variable i equals 3.
for i in range(10):
if i == 3:
break
print(i)
0
1
2
In this case, the for loop starts at 0 and increments by 1 on each iteration. When i equals 3, the break statement is executed, and the loop is terminated.
This example demonstrates breaking out of a loop early based on a user-defined condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
if number == 5:
print("Found 5! Exiting loop.")
break
print(number)
1
2
3
4
Found 5! Exiting loop.
Here, the loop is searching for the number 5. When it is found, the break statement is executed, and the loop is terminated.
This example shows how the break statement can be used within a while loop.
i = 1
while i <= 10:
print(i)
if i == 6:
break
i += 1
1
2
3
4
5
6
In this example, the while loop continues to execute until i equals 6. At this point, the break statement is encountered, and the loop terminates.
This example demonstrates how the break statement behaves when used inside nested loops.
for i in range(3):
for j in range(3):
if j == 2:
break
print(f"i = {i}, j = {j}")
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
In this example, there are two nested for loops. The break statement is inside the inner loop and breaks out of the inner loop when j equals 2, but the outer loop continues to execute.