Skip to content

Python skip to next iteration | Example code

Use the continue statement inside the loop to skip to the next iteration in Python. However, you can say it will skip the current iteration, not the next one. But what we want to skip the code for this iteration in the loop.

So continue statement suits this situation.

Example skip to next iteration in Python

Simple example code.

Example 1

Skip print() if number is 2.

for i in range(1, 5):
    if i == 2:
        continue
    print(i)

Output:

Python skip to next iteration

Example 2

Python program to display only odd numbers.

for num in [1, 2, 3, 4, 5, 6]:
    # Skipping the iteration if number is even
    if num % 2 == 0:
        continue
    print(num)

Output:

1
3
5

Example 3

Get the positive numbers list from the given list of numbers.

nums = [7, 3, -1, 8, -9]
positive_nums = []

for num in nums:
    if num < 0:  # skips if negative num
        continue
    positive_nums.append(num)

print(positive_nums)

Output: [7, 3, 8]

Do comment if you have any doubts or suggestions on this Python iteration tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

1 thought on “Python skip to next iteration | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading