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.
This is useful when you want to process most items in a loop but want to ignore specific ones based on a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0:
continue
print(f"Processing odd number: {number}")
print("Loop finished.")Here, the loop iterates through numbers 1 to 10. If a number is even (number % 2 == 0), the continue statement is executed. This skips the print statement for that even number and moves to the next number. Only the odd numbers are printed.
graph TD;
A[Start Loop] --> B{Check Condition};
B -- True --> C[Process Item];
C --> D{Skip This Iteration?};
D -- True --> E[CONTINUE to Next Iteration];
D -- False --> F[Process Item Further];
F --> G[End of Iteration];
E --> B;
G --> B;
B -- False --> H[Continue After Loop];
Let's summarize the main distinctions:
break: Terminates the entire loop immediately.continue: Skips the rest of the current iteration and moves to the next one.
Both break and continue are powerful tools for managing the flow of your loops, allowing you to write more dynamic and efficient code.