How to Use continue in Python for and while Loops

Python Python Basics

In programming, the continue statement is used to skip the rest of the code inside a loop for the current iteration only. It then continues with the next iteration of the loop. This can be very useful when you want to bypass some specific conditions during your loops.

Table of Contents

Using continue in Python for Loop

The continue statement is often used within a for loop, which allows us to skip over certain parts of our code based on the condition we specify. Here’s an example:


for i in range(10):
    if i % 2 == 0: # If the number is even
        continue   # Skip the rest of this iteration
    print(i)       # This will only be executed for odd numbers

In this code, we’re looping over a range from 0 to 9. For each number in that range, we check if it’s divisible by 2 (which means it’s an even number). If it is, the continue statement causes us to skip the rest of the current iteration and move directly to the next one. As a result, only odd numbers are printed out.

Using continue in Python while Loop

The continue statement can also be used within a while loop. Here’s an example:


i = 0
while i < 10:
    i += 1
    if i % 2 == 0: # If the number is even
        continue   # Skip the rest of this iteration
    print(i)       # This will only be executed for odd numbers

In this code, we’re using a while loop to iterate over a range from 1 to 9. For each number in that range, we check if it’s divisible by 2 (which means it’s an even number). If it is, the continue statement causes us to skip the rest of the current iteration and move directly to the next one. As a result, only odd numbers are printed out.

Conclusion

The continue statement in Python can be very useful for controlling the flow of your loops based on certain conditions. By skipping over certain parts of your code, you can simplify your logic and make your programs more efficient. However, it’s important to use continue judiciously as overuse can lead to confusion and make your code harder to understand.

To top