Break in Python
In Python, the break statement allows you to exit a loop immediately.
break
When the interpreter encounters a break statement, it transfers control to the first statement following the loop.
You can use the break statement in both for and while loops.
Note: The break statement exits the entire loop. To skip just one iteration of the loop, use the continue statement.
Practical Examples
Here are some practical examples of using the break statement in for and while loops.
Example 1 (while loop)
This while loop is designed to run for 6 iterations.
However, at the third iteration, the break statement forces an exit from the loop.
- x = 0
- while x < 6:
- x += 1
- if x == 3: break
- print(x)
- print("end")
The output of the script is:
1
2
end
The break statement is particularly useful in while loops to avoid infinite loops.
Example 2 (for loop)
This for loop is set to run for 5 iterations.
However, at the third iteration, the break statement causes an early exit from the loop.
- for i in range(1, 5):
- if i == 3: break
- print(i)
The output of the script is:
1
2
And so on.