Skip to content

Continue Statement in Loop in Python

Seamless Iteration: Demystifying the continue Statement in Python Loops

In the realm of Python loops, the continue statement stands as a powerful tool, allowing developers to gracefully skip the rest of the code within a loop for the current iteration and move on to the next iteration. Unlike the break statement, which exits the loop entirely, continue provides a means to bypass specific actions within the loop while allowing it to continue with subsequent iterations. In this comprehensive guide, weโ€™ll explore the syntax, functionality, and best practices associated with the continue statement in Python loops.

What Is the continue Statement?

The continue statement is a control flow statement that allows you to skip the rest of the code inside a loop for the current iteration only. When a continue statement is encountered inside a loop, the program execution skips the statements inside the loop for the current iteration and returns to the top of the loop for the next iteration.

Syntax of continue

The syntax of a continue statement in Python:

continue Statement in while Loop

continue_while_loop.py
while test_expression:
    Body of while
    if test_expression:
        continue
continue_while_loop.py
while test_expression:
    Body of while
    if test_expression:
        continue

continue Statement in for Loop

continue_for_loop.py
for val in sequence:
    Body of for
    if test_expression:
        continue
continue_for_loop.py
for val in sequence:
    Body of for
    if test_expression:
        continue

Here, valval is the variable that takes the value of the item inside the sequence on each iteration.

We generally use continue statement inside the loop when we want to skip the rest of the code inside the loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

Example of continue Statement in Python

Here is an example of a continue statement in python:

continue Statement in while Loop

continue_while_loop.py
# continue in while loop
i = 0
while i < 10:
    i += 1
    if i == 5:
        continue
    print(i)
continue_while_loop.py
# continue in while loop
i = 0
while i < 10:
    i += 1
    if i == 5:
        continue
    print(i)

Output:

command
C:\Users\Your Name> python continue_while_loop.py
0
1
2
3
4
6
7
8
9
command
C:\Users\Your Name> python continue_while_loop.py
0
1
2
3
4
6
7
8
9

In the above example, the continue statement skips the rest of the code inside the loop for the current iteration when the value of ii is 5. Hence, 5 is not printed in the output. The loop continues until its condition becomes false. Notice that the value of ii is incremented before the continue statement is encountered.

continue Statement in for Loop

continue_for_loop.py
# continue in for loop
for val in "string":
    if val == "i":
        continue
    print(val)
print("The end")
continue_for_loop.py
# continue in for loop
for val in "string":
    if val == "i":
        continue
    print(val)
print("The end")

Output:

command
C:\Users\Your Name> python continue_for_loop.py
s
t
r
n
g
The end
command
C:\Users\Your Name> python continue_for_loop.py
s
t
r
n
g
The end

In this program, we iterate through the valval variable. We check if the value of the valval variable is ii. If it is, we continue with the next iteration. Otherwise, we print the value of valval. We continue this until the end of the string is reached. Hence, we see in our output that the letter ii is not printed. The loop continues until the end of the string is reached.

Use Cases for the continuecontinue Statement

1. Skipping Unnecessary Computations:

The continuecontinue statement is beneficial when certain computations or operations can be skipped for specific conditions.

continue_odd_numbers.py
numbers = [1, 2, 3, 4, 5]
 
for number in numbers:
    if number % 2 == 0:
        continue
    print(f"{number} is an odd number.")
continue_odd_numbers.py
numbers = [1, 2, 3, 4, 5]
 
for number in numbers:
    if number % 2 == 0:
        continue
    print(f"{number} is an odd number.")

Output:

command
C:\Users\Your Name> python continue_odd_numbers.py
1 is an odd number.
3 is an odd number.
5 is an odd number.
command
C:\Users\Your Name> python continue_odd_numbers.py
1 is an odd number.
3 is an odd number.
5 is an odd number.

In this example, the loop prints only the odd numbers in the list, skipping even numbers using continuecontinue.

2. Avoiding Errors or Unwanted Actions:

When processing data or elements in a loop, the continuecontinue statement can be used to avoid errors or unwanted actions based on specific conditions.

continue_invalid_grades.py
grades = [85, 92, "invalid", 78, 96]
 
for grade in grades:
    if not isinstance(grade, int):
        print(f"Invalid grade: {grade}")
        continue
    # Code to process valid grades
    print(f"Processed grade: {grade}")
continue_invalid_grades.py
grades = [85, 92, "invalid", 78, 96]
 
for grade in grades:
    if not isinstance(grade, int):
        print(f"Invalid grade: {grade}")
        continue
    # Code to process valid grades
    print(f"Processed grade: {grade}")

Output:

command
C:\Users\Your Name> python continue_invalid_grades.py
Processed grade: 85
Processed grade: 92
Invalid grade: invalid
Processed grade: 78
Processed grade: 96
command
C:\Users\Your Name> python continue_invalid_grades.py
Processed grade: 85
Processed grade: 92
Invalid grade: invalid
Processed grade: 78
Processed grade: 96

In this example, the loop processes only valid integer grades, skipping the processing of the invalid grade with continuecontinue.

3. Handling Special Cases:

When dealing with special cases or edge conditions, the continuecontinue statement can be applied to bypass certain iterations.

continue_skip_user_response.py
user_responses = ["yes", "no", "skip", "yes", "no"]
 
for response in user_responses:
    if response == "skip":
        print("Skipped user response.")
        continue
    # Code to process valid responses
    print(f"Processed response: {response}")
continue_skip_user_response.py
user_responses = ["yes", "no", "skip", "yes", "no"]
 
for response in user_responses:
    if response == "skip":
        print("Skipped user response.")
        continue
    # Code to process valid responses
    print(f"Processed response: {response}")

Output:

command
C:\Users\Your Name> python continue_skip_user_response.py
Processed response: yes
Processed response: no
Skipped user response.
Processed response: yes
Processed response: no
command
C:\Users\Your Name> python continue_skip_user_response.py
Processed response: yes
Processed response: no
Skipped user response.
Processed response: yes
Processed response: no

Here, the loop processes all user responses except for the one marked as โ€œskip.โ€

Best Practices for Using the continue Statement

1. Use continuecontinue Sparingly:

While the continuecontinue statement is a valuable tool, its usage should be approached with care. Overusing continuecontinue can lead to code that is challenging to understand and maintain.

2. Clear Documentation of Skipped Conditions:

When utilizing continuecontinue, provide clear comments or documentation explaining the conditions under which the remaining code should be skipped. This aids in code readability and understanding.

continue_skip_negative_numbers.py
numbers = [1, 2, 3, -4, 5, -6]
# Skip processing for negative numbers
for number in numbers:
    if number < 0:
        continue
    print(f"Processed number: {number}")
continue_skip_negative_numbers.py
numbers = [1, 2, 3, -4, 5, -6]
# Skip processing for negative numbers
for number in numbers:
    if number < 0:
        continue
    print(f"Processed number: {number}")

Output:

command
C:\Users\Your Name> python continue_skip_negative_numbers.py
Processed number: 1
Processed number: 2
Processed number: 3
Processed number: 5
command
C:\Users\Your Name> python continue_skip_negative_numbers.py
Processed number: 1
Processed number: 2
Processed number: 3
Processed number: 5

In this example, the loop processes only positive numbers, skipping negative numbers using continuecontinue.

3. Consider Alternative Control Flow:

In some scenarios, alternative control flow mechanisms might provide a more readable and maintainable solution than relying on continuecontinue.

4. Keep Code Within the Loop Concise:

When using continuecontinue, itโ€™s advisable to keep the code within the loop concise. Long and complex code structures can make it challenging to understand the flow of the loop.

Conclusion

The continuecontinue statement in Python loops offers an elegant solution for skipping specific actions within an iteration while allowing the loop to continue with subsequent iterations. When used judiciously, it enhances code clarity and efficiency. As you explore Python programming, experiment with the continuecontinue statement in various scenarios to gain a deeper understanding of its applications.

Incorporate the continuecontinue statement where it makes sense, considering the readability and maintainability of your code. For more insights and practical examples, check out our tutorials on Python Central Hub!

Was this page helpful?

Let us know how we did