How to Skip to the Next Iteration in a Python For Loop?

Estimated read time 2 min read

To skip to the next iteration in a Python for loop, you can use the continue statement. The continue statement is used to skip the rest of the code in the current iteration of the loop and move on to the next iteration.

Here’s an example of using the continue statement to skip to the next iteration in a Python for loop:

# loop through a list and print only the even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
    if number % 2 != 0:
        continue
    print(number)

In this example, we loop through a list of numbers using a for loop. Inside the loop, we use an if statement to check if the current number is odd (i.e., if the remainder of the number divided by 2 is not 0). If the number is odd, we use the continue statement to skip the rest of the code in the current iteration and move on to the next iteration. If the number is even, we print the number.

The output of this code is:

2
4
6
8
10

Note that the continue statement only skips the rest of the code in the current iteration of the loop. It does not skip the entire loop. If you want to skip the entire loop under certain conditions, you can use the break statement instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply