capypad
0 day streak
python / beginner
Snippet

Breaking Out of a Loop

The break statement is used to exit a loop immediately, regardless of whether the loop condition is still met.

snippet.py
python
1
2
3
4
5
6
val = 0
while val < 10:
if val == 2:
break
print(val)
val = val + 1
Breakdown
1
if val == 2:
Check if the variable has reached the value 2.
2
break
Stop the loop execution immediately.
3
val = val + 1
Increment the variable to move to the next step.