How to Use Continue in Python to Start a Loop Over

Python continue statement is one of the loop statements that control the flow of the loop. More specifically, the continue statement skips the "rest of the loop" and jumps into the beginning of the next iteration.

Unlike the break statement, the continue does not exit the loop.

For example, to print the 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 function 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:

Python continue statement

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.

Using the continue statement may sometimes be a key part to make an algorithm work. Sometimes it just saves resources because it prevents running excess code.

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 instance, you can use the continue statement to skip printing even 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 the continue statement is essentially the same as putting the code into an if-else block.

In simple cases, it's usually a better idea to use an if-else statement, instead of the continue!

For instance, let's loop through numbers from 1 to 10, and print the type oddity of the numbers:

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 statement:

for num in range(1, 10):     if num % 2 == 0:         print("Even number: ", num)     else:         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

As you can see, the latter approach provides a cleaner way to express your intention. By looking at this piece of code it is instantly clear what it does. However, if you look at the former approach with the continue statements, you need to scratch your head a bit before you see what is going on.

This is a great example of when you can use an if-else statement instead of using the continue statement.

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

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

You see it is cleaner to use an if-check here as well, rather than mixing it up with the continue statement:

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 good use cases for the continue statement.

When Use Continue Python

As stated earlier, you can replace the continue statement with if-else statements.

For example, this piece of code:

if condition:     action()     continue do_something()

Does the same as this one:

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

In simple cases, using if-else over a continue is a good idea. But there are definitely some use cases for the continue statement too.

For example:

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

Let's see examples of both of these.

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 pyramid-shaped chaos:

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 mess is infeasible to manage.

However, you can make the above code cleaner and flatter using the continue statement:

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 the continue statement.

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

If you need to handle exceptions in a loop, use the continue statement 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 function 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 function:

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

This is useful if the last print function was something you should not accidentally run when an error occurs.

Conclusion

Today you learned how to use the continue statement in Python.

To recap, the continue statement in Python skips "the rest of the loop" and starts an iteration. This is useful if the rest of the loop consists of unnecessary code.

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 function if it encounters an even number.

However, an if-else statement is usually better than using an if statement with a continue statement. However, with multiple conditions, the continue statement prevents nested if-else blocks that are infeasible to manage.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

creedfolen1989.blogspot.com

Source: https://www.codingem.com/python-continue-statement/

0 Response to "How to Use Continue in Python to Start a Loop Over"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel