The break
statement in Python is used to exit a loop prematurely when a certain condition is met. Once the break
statement is encountered, the loop stops immediately, and the program continues with the next statement after the loop.
Example:
Let’s say you have a loop that prints numbers from 1 to 10, but you want to stop the loop when the number 5 is reached.
for i in range(1, 11):
if i == 5:
break # Exit the loop when i is 5
print(i)
Explanation:
- The loop starts with
i
being 1 and goes up to 10. - When
i
reaches 5, theif
conditioni == 5
becomesTrue
. - The
break
statement is executed, and the loop is terminated. - Only the numbers 1 to 4 are printed because the loop stops when
i
is 5.
Output:
1
2
3
4
In this example, the break
statement prevents the loop from continuing once i
equals 5.