Lesson 12 of 21 · 2 min
break — Exit the Loop Immediately
The WHY — Why break?
Sometimes you are searching for something and once you find it, there is no reason to keep looking. break stops the loop immediately and jumps to the code after the loop.
numbers = [3, 7, 2, 9, 1, 5, 8, 4] # list of numbers to search through
target = 9 # the number we are looking for
for num in numbers: # go through each number
if num == target: # check if this is the number we want
print(f"Found {target}!") # report that we found it
break # STOP the loop — no need to keep searching
print(f"Checking {num}...") # this prints for every number before we find it
Output: Checking 3... Checking 7... Checking 2... Found 9!
Without break, the loop would continue checking 1, 5, 8, and 4 even after finding 9 — wasted effort.
