The Break Statement
What you'll learn: How to exit a loop immediately when a specific condition is met, without waiting for the loop's normal termination condition.
What is the Break Statement?
When you're running a loop, you normally rely on the loop's condition (in a while loop) or its iteration count (in a for loop) to determine when to stop. But sometimes you need to exit early — to abandon the loop the moment you find what you're looking for or encounter a special situation.
The break statement does exactly that: it immediately terminates the loop and continues execution with whatever code comes after the loop.
Why Use Break?
Think of it like searching for your keys in a drawer. You don't need to check every item once you've found them — you stop searching immediately. Without break, your loop would pointlessly continue even after achieving its goal.
Example pattern:
while something_is_true:
if found_what_we_need:
break
# continue normal loop work
When the break executes, the loop stops instantly, even if the while condition is still true or the for loop hasn't finished all iterations.
Common Use Case
Searching through items until you find a match:
count = 0
while count < 100:
if count == 50:
break # exits loop immediately
count = count + 1
# loop ends at 50, not 100
Key Takeaway: The break statement lets you exit a loop immediately when a condition is met, providing more flexible control over loop execution than relying solely on the loop's main condition.