The continue
statement is a control flow tool in Python that skips the rest of the current iteration in a loop and proceeds to the next iteration.
Example
for number in range(10):
if number % 2 == 0: # Skip even numbers
continue
print(number)
Output:
1
3
5
7
9
Syntax
continue
No additional arguments are required. When continue
is executed, it moves the loop to the next iteration immediately.
Why Use continue?
The continue
statement is useful when you need to bypass the remaining code in a loop for specific cases while allowing the loop to continue running for other iterations. It helps to write clean and concise code by avoiding deeply nested conditions. Lets see some example of Python continue.
1. Skipping Invalid Data
Scenario: Processing a list of numbers where negative values should be ignored.
numbers = [10, -5, 15, -20, 25]
for num in numbers:
if num < 0:
continue # Skip negative numbers
print(f"Processing: {num}")
Output:
Processing: 10
Processing: 15
Processing: 25
2. Avoiding Specific Conditions
Scenario: Iterating through a range of numbers but skipping multiples of 3.
for i in range(1, 11):
if i % 3 == 0:
continue # Skip multiples of 3
print(i)
Output:
1
2
4
5
7
8
10
3. Skipping on Validation Errors
Scenario: Iterating through user input data, skipping entries that are invalid.
inputs = ["123", "abc", "456", "def"]
for value in inputs:
if not value.isdigit():
continue # Skip non-numeric inputs
print(f"Valid number: {value}")
Output:
Valid number: 123
Valid number: 456
Key Notes
- Simplifies Code: Avoids excessive nesting by skipping unnecessary iterations.
- Use with Care: Ensure skipping an iteration doesn’t disrupt the logic of your program.
- Combine with Loops: Works with both
for
andwhile
loops for maximum flexibility. - Avoid Overuse: Overusing continue can make your code harder to understand. Use it only when it simplifies the logic.
By understanding and using the continue
statement effectively, you can manage loops dynamically, making your code more readable and efficient.