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
1
2
3
4
5
6
val = 0while val < 10:if val == 2:breakprint(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.