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 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.
graph TD;
A[Start Loop] --> B{Check Condition};
B -- True --> C[Process Item];
C --> D{Found Target?};
D -- True --> E[Print Message];
E --> F[BREAK Loop];
D -- False --> B;
F --> G[Continue After Loop];
B -- False --> G;
Unlike break, which exits the entire loop, the continue statement only skips the current iteration of the loop. When continue is encountered, Python stops executing the rest of the code within the current iteration and moves on to the next iteration of the loop. If it's a while loop, it will re-evaluate the while condition.