continue

For Loops

continue

In this tutorial, we'll skip to the next loop item.

continue skips the rest of the current loop run and moves to the next item.

numbers = [1, 2, 3, 4]

for number in numbers:
    if number == 3:
        continue
    print(number)

Output:

1
2
4

When number is 3, Python skips the print().

Filtering Items

continue is useful when you want to ignore certain values:

words = ["apple", "", "banana", ""]

for word in words:
    if word == "":
        continue
    print(word)

Output:

apple
banana

Keeping Code Less Nested

Without continue, you might write:

for word in words:
    if word != "":
        print(word)

Both versions are fine. continue becomes more helpful when the loop body is longer.

Another Example

Imagine you only want to process passing scores:

scores = [80, 42, 91, 35]

for score in scores:
    if score < 50:
        continue
    print("Passing score:", score)

The failing scores are skipped.

Common Mistake

continue does not stop the whole loop. It only skips to the next item. If you want to stop completely, use break.

Also be careful where you place code. Any code after continue inside the same loop run will be skipped:

for number in [1, 2, 3]:
    if number == 2:
        continue
    print("Number:", number)

The print line does not run for 2.

Practice

Loop over numbers from 1 to 10 and print only the odd numbers.