Python Break and Continue Statements
When working with loops in Python, there are situations where you might want to:
- Skip the current iteration and move to the next one
- Exit the loop completely before its normal completion
Python provides two special statements for these situations: continue
and break
. These statements give you more fine-grained control over your loops, making your code more efficient and expressive.
The break
Statement
The break
statement allows you to exit a loop immediately, regardless of the loop condition.
How break
Works
When Python encounters a break
statement:
- It immediately terminates the loop containing it
- Program control flows to the statement immediately after the loop
- If the
break
is inside nested loops, it only exits from the innermost loop
Basic Example of break
for number in range(1, 10):
if number == 5:
print("Found 5! Breaking the loop...")
break
print(f"Current number: {number}")
print("Loop ended")
Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5! Breaking the loop...
Loop ended
Notice how the loop exits as soon as number
equals 5, and the program continues with the statements after the loop.
The continue
Statement
The continue
statement skips the rest of the code inside the current loop iteration and jumps to the next iteration.
How continue
Works
When Python encounters a continue
statement:
- It skips the remaining code in the current loop iteration
- Control returns to the top of the loop for the next iteration
- The loop condition is re-evaluated as usual
Basic Example of continue
for number in range(1, 10):
if number % 2 == 0: # If number is even
continue # Skip the rest of the loop for even numbers
print(f"Current number: {number}")
print("Loop ended")
Output:
Current number: 1
Current number: 3
Current number: 5
Current number: 7
Current number: 9
Loop ended
In this example, the continue
statement skips printing even numbers, so only odd numbers are displayed.
Practical Applications
Example 1: Input Validation with break
Here's how you might use break
to validate user input:
while True:
user_input = input("Enter a positive number (or 'q' to quit): ")
if user_input.lower() == 'q':
print("Exiting the program...")
break
try:
number = float(user_input)
if number <= 0:
print("Please enter a POSITIVE number.")
else:
print(f"You entered: {number}")
except ValueError:
print("That's not a valid number. Try again.")
print("Program terminated.")
Sample Output:
Enter a positive number (or 'q' to quit): -5
Please enter a POSITIVE number.
Enter a positive number (or 'q' to quit): hello
That's not a valid number. Try again.
Enter a positive number (or 'q' to quit): 10.5
You entered: 10.5
Enter a positive number (or 'q' to quit): q
Exiting the program...
Program terminated.
Example 2: Processing a List with continue
Here's how you might use continue
to filter items while processing a list:
def process_scores(scores):
passing_scores = []
for score in scores:
# Skip invalid scores
if score < 0 or score > 100:
print(f"Invalid score detected: {score}. Skipping.")
continue
# Skip failing scores
if score < 60:
continue
# Process passing scores
passing_scores.append(score)
if passing_scores:
average = sum(passing_scores) / len(passing_scores)
return f"Average of passing scores: {average:.2f}"
else:
return "No passing scores found."
# Test the function
test_scores = [75, 90, -5, 45, 110, 60, 82]
result = process_scores(test_scores)
print(result)
Output:
Invalid score detected: -5. Skipping.
Invalid score detected: 110. Skipping.
Average of passing scores: 76.75
Using break
and continue
with else
in Loops
Python has a unique feature where you can use an else
clause with loops. The else
block executes when the loop completes normally (without encountering a break
).
for number in range(2, 10):
for x in range(2, number):
if number % x == 0:
print(f"{number} equals {x} * {number//x}")
break
else:
# This runs if no break occurred (number is prime)
print(f"{number} is a prime number")
Output:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Common Pitfalls and Best Practices
Pitfalls to Avoid
- Infinite Loops: Be careful when using
continue
inwhile
loops. Ensure your loop condition eventually becomesFalse
.
# Problematic code - infinite loop!
counter = 0
while counter < 5:
if counter < 3:
continue # Counter never increases if less than 3!
counter += 1
- Missing Loop Termination: Ensure loops with
break
will eventually terminate.
Best Practices
-
Use Comments: Always document why you're using
break
orcontinue
. -
Limit Usage: Excessive use of
break
andcontinue
can make code harder to read. -
Consider Alternatives: Sometimes restructuring your loop logic is clearer than using
break
orcontinue
.
# Instead of:
for item in items:
if not some_condition(item):
continue
# process item...
# Consider:
for item in items:
if some_condition(item):
# process item...
Summary
break
immediately exits the loop entirelycontinue
skips the current iteration and moves to the next one- These statements help you control loop flow with greater precision
- When combined with conditions, they make your loops more efficient and expressive
- The loop's
else
clause executes only if the loop completes normally (withoutbreak
)
Practice Exercises
-
Write a program that asks the user for numbers until they enter 0, but skips negative numbers.
-
Create a program that looks for the first palindrome word in a list of words.
-
Implement a simple calculator that continues until the user enters "exit".
-
Write a program that generates random numbers until it gets a number divisible by both 3 and 5.
Additional Resources
- Python Documentation on Control Flow
- Python Loop Techniques
- Python Style Guide (PEP 8) for best practices
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)