Python Continue Statement

man siting facing laptop

Python continue is a loop statement. It skips the “rest of the loop” and jumps into the beginning of the next iteration of the loop. Unlike break statement, continue does not exit the loop.

For example, to print odd numbers, use continue to skip printing the even numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

This loop skips the print statement when it encounters an even number (a number divisible by 2):

1
3
5
7
9

Here is an illustration of how the above code works when n is even:

Continue Statement in More Detail

In Python, the continue statement jumps out of the current iteration of a loop to start the next iteration.

A typical use case for a continue statement is to check if a condition is met, and skip the rest of the loop based on that.

In Python, the continue statement can be used with both for and while loops:

while condition:
    if other_condition:
        continue
for elem in iterable:
    if condition:
        continue

For example, you can use continue to print odd numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Output:

1
3
5
7
9

Continue vs If-Else in Python

The continue statement behaves in the same way as an if-else statement. Using a continue is essentially the same as putting everything that follows into an if/else block.

Keep in mind, in simple cases it’s usually a better idea to use a regular if-else statement, instead of using if with continue!

For instance, let’s loop through numbers from 1 to 10, and print the type of the number (odd/even):

Here is the continue approach:

for num in range(1, 10):
    if num % 2 == 0:
        print("Even number: ", num)
        continue
    print("Odd number: ", num)

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

Then, let’s convert this approach to an if-else approach:

for num in range(1, 10):
    if num % 2 == 0:
        print("Even number: ", num)
    else:
        print("Odd number: ", num)

This approach is a bit more cleaner than the continue approach.

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

Also, if you take a look at the earlier example of printing odd numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

You can see it’s actually cleaner to use an if check here as well, rather than mixing in the continue:

n = 0
while n < 10:
    n += 1
    if n % 2 != 0:
        print(n)

But now you may wonder why should you use continue if it only makes code more unreadable. Let’s see some use cases.

When Use Continue Python

As stated earlier, continue can be replaced with if-else statements.

For example:

if condition:
    action()
    continue
do_something()

Is the same as:

if not condition:
    action()
else:
    do_something()

In simple cases, using if-else over a continue is usually a better idea. But there are definitely use cases for continue as well:

  1. You can avoid nested if-elses with continue.
  2. Continue can help you with exception handling in a for loop.

Let’s see what these mean.

1. Avoid Nested If-Else Statements in a Loop with Continue in Python

Imagine you have multiple conditions where you want to skip looping. If you solely rely on if-else statements, your code becomes a mess:

for entry in data:
    if not condition1:
        action1()
        if not condition2:
            action2()
            if not condition3:
                action3()
            else:
                statements3()
        else:
            statements2()
    else:
        statements1()

This is every developer’s nightmare. A nested if-else structure that is infeasible to manage.

However, you can make the above code cleaner with the help of continue:

for entry in data:
    if condition1:
        statements1()
        continue
    action1()
    
    if condition2:
        statements2()
        continue
    action2()
    
    if condition3:
        statements3()
        continue
    action3()

Now, instead of having a nested structure of if-else statements, you have a flat structure of if statements only. This means the code is way more understandable and easier to maintain—thanks to continue.

2. Continue in Error Handling—Try, Except, Continue

If you need to handle exceptions in a loop, use continue to skip the rest of the loop.

For example, take a look at this piece of code that handles errors in a loop:

for number in [1,2,3]:
  try:
    print(x)
  except:
    print("Exception was thrown...")
  print("... But I don't care!")

Now the loop executes the last print statement regardless of whether an exception is thrown or not:

Exception was thrown...
... But I don't care!
Exception was thrown...
... But I don't care!
Exception was thrown...
... But I don't care!

To avoid this, use the continue statement in the except block. This skips the rest of the loop when an exception occurs.

for number in [1,2,3]:
  try:
    print(x)
  except:
    print("Exception was thrown...")
    continue
  print("... But I don't care!")

Now the loop skips the last print statement:

Exception was thrown...
Exception was thrown...
Exception was thrown...

Conclusion

The continue statement in Python skips “the rest of the loop” and starts a new round.

For example, you can skip printing even numbers and only print the odd numbers by:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Here the loop skips the last print statement if it encounters an even number.

A basic if-else statement is usually cleaner than using if with a continue statement. However, with multiple conditions the continue statement can save you from nested if-else blocks.

If you want to see continue in use by Python’s developers, make sure to source dive the Python’s codebase.

For example, here they use continue in a try-except structure to skip the rest of a loop with a faulty value. And here is one where they use continue in an if-statement to avoid putting the rest of the code into an if block to keep the code more readable.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *