
Controlling Loops: Break and Continue
So far, you've learned about for and while loops, which are fantastic for repeating actions. But what if you need more fine-grained control over how these loops behave? Sometimes, you might want to exit a loop early, or skip a particular iteration without stopping the entire loop. That's where the break and continue statements come in!
The break Statement: Exiting Loops Prematurely
The break statement is used to immediately terminate the current loop. When Python encounters a break statement, it stops executing the loop altogether and continues with the code that comes after the loop. Think of it as an emergency exit for your loop.
A common use case for break is when you're searching for something within a loop and want to stop as soon as you find it, rather than continuing to check the remaining items.
numbers = [1, 5, 10, 15, 20, 25]
for number in numbers:
if number == 15:
print("Found the number 15!")
break
print(f"Checking {number}...")
print("Loop finished.")In this example, the loop iterates through the numbers list. When number becomes 15, the if condition is met, a message is printed, and break is executed. The loop immediately stops, and the print("Loop finished.") statement is executed. Notice that the numbers after 15 (20 and 25) are never checked.