ZetCode

Python continue statement

last modified November 29, 2026 Python 3.15

In this article we show how to use the continue statement to skip the rest of a loop iteration.

The continue statement ends the current iteration of the nearest enclosing for or while loop and starts the next one. A for loop moves on to the next item; a while loop evaluates its condition again. Unlike break, which ends the whole loop, continue skips only one pass through the loop body.

The statement is typically used to filter items: the loop body first checks whether the current item should be processed and skips it if not. The Python control flow article introduces continue together with the other loop statements.

Skipping items in a for loop

In the first example, we print the odd numbers from one to ten by skipping the even ones.

odd_numbers.py
for n in range(1, 11):
    if n % 2 == 0:
        continue
    print(n, end=" ")

print()

When n is even, continue jumps back to the top of the loop and the print call is not reached. The final print after the loop ends the output line.

$ python odd_numbers.py
1 3 5 7 9

continue in a while loop

In a while loop, continue jumps to the loop condition. Any code that moves the loop forward must run before the continue; otherwise the loop never ends.

while_counter.py
n = 0

while n < 10:
    n += 1
    if n % 3 == 0:
        continue
    print(n, end=" ")

print()

The program prints the numbers from one to ten except the multiples of three. The counter is increased at the top of the body, before the test. If the n += 1 line were placed at the end of the body, the first continue at n == 3 would skip it, and the loop would test the same value forever.

$ python while_counter.py
1 2 4 5 7 8 10

Deeply nested conditions

Filtering loops are often written with nested if statements. The example parses simple key = value settings and must ignore empty lines, comments, and lines without an equals sign.

nested_ifs.py
lines = [
    "host = example.com",
    "",
    "# the default port",
    "port = 8080",
    "debug",
    "user = admin",
]

for line in lines:
    if line:
        if not line.startswith("#"):
            if "=" in line:
                key, value = line.split("=")
                print(f"{key.strip()}: {value.strip()}")

Every condition adds a level of indentation, and the real work sits at the bottom of a staircase of if statements. Adding a message for malformed lines would require an else branch far away from the condition it belongs to.

$ python nested_ifs.py
host: example.com
port: 8080
user: admin

Guard clauses with continue

With continue, each condition becomes a guard clause at the top of the loop body. A guard rejects an unwanted item and the main code stays at one level of indentation.

guard_clauses.py
lines = [
    "host = example.com",
    "",
    "# the default port",
    "port = 8080",
    "debug",
    "user = admin",
]

for line in lines:
    if not line:
        continue
    if line.startswith("#"):
        continue
    if "=" not in line:
        print(f"skipping malformed line: {line!r}")
        continue

    key, value = line.split("=")
    print(f"{key.strip()}: {value.strip()}")

The loop rejects empty lines, then comments, then malformed lines. Each check is independent and reads from top to bottom. The malformed line now gets its own message next to the condition that detects it. Whatever passes all guards is processed at the end of the body.

$ python guard_clauses.py
host: example.com
port: 8080
skipping malformed line: 'debug'
user: admin

Skipping invalid data

The continue statement also works inside an except clause. A loop that converts data can record a bad value and move on to the next one instead of stopping.

bad_records.py
records = ["12", "7", "n/a", "30", "", "4.5", "9"]

total = 0
errors = []

for record in records:
    try:
        value = int(record)
    except ValueError:
        errors.append(record)
        continue
    total += value

print("total:", total)
print("rejected:", errors)

The int function raises ValueError for values that are not whole numbers. The handler stores the rejected value and continues with the next record, so the addition below runs only for valid numbers. See Python exceptions for more about handling errors.

$ python bad_records.py
total: 58
rejected: ['n/a', '', '4.5']

Nested loops

A continue statement affects only the innermost loop that contains it. The outer loop and the code after the inner loop are not skipped.

nested.py
seats = [
    ["A1", "A2", "A3"],
    ["B1", "B2", "B3"],
]
taken = ["A2", "B1", "B3"]

for row in seats:
    for seat in row:
        if seat in taken:
            continue
        print(seat, end=" ")
    print("| end of row")

The inner loop skips the taken seats and prints the free ones. The continue moves on to the next seat in the same row; the print("| end of row") call after the inner loop runs for every row.

$ python nested.py
A1 A3 | end of row
B2 | end of row

continue and the else clause

The else clause of a loop runs when the loop ends without break. Skipping iterations with continue does not change that; the loop still runs to its end.

loop_else.py
scores = [78, -1, 92, 85, -1, 64]

for score in scores:
    if score < 0:
        continue
    print("score", score)
else:
    print("all scores processed")

The negative scores mark missing results and are skipped. Even though two iterations end with continue, the loop finishes normally and the else clause runs.

$ python loop_else.py
score 78
score 92
score 85
score 64
all scores processed

continue and finally

When continue leaves a try block, the finally clause runs before the next iteration starts. Cleanup code is not skipped.

finally_runs.py
files = ["notes.txt", "photo.png", "todo.txt"]

for name in files:
    try:
        if not name.endswith(".txt"):
            print("skipping", name)
            continue
        print("reading", name)
    finally:
        print("closing", name)

The image file is skipped with continue, but the finally clause still prints the closing message for it. The reverse, a continue inside a finally clause, can silently discard an exception and triggers a SyntaxWarning since Python 3.14; the break article shows the problem.

$ python finally_runs.py
reading notes.txt
closing notes.txt
skipping photo.png
closing photo.png
reading todo.txt
closing todo.txt

Summarizing a log

The last example combines the previous ideas. It counts the entries of a log by level, skips the debug messages, and counts the malformed lines.

log_summary.py
log = [
    "INFO server started",
    "DEBUG cache warmed",
    "WARNING disk at 85%",
    "garbage",
    "ERROR connection lost",
    "DEBUG retrying",
    "INFO connection restored",
    "ERROR timeout",
]

counts = {}
skipped = 0

for entry in log:
    if " " not in entry:
        skipped += 1
        continue

    level, message = entry.split(" ", 1)
    if level == "DEBUG":
        continue

    counts[level] = counts.get(level, 0) + 1
    if level == "ERROR":
        print("error:", message)

print(counts)
print("malformed lines:", skipped)

The first guard skips lines without a space, which cannot be split into a level and a message, and counts them. The second guard drops the debug entries without counting them. The remaining entries are counted in a dictionary, and the errors are printed as they are found.

$ python log_summary.py
error: connection lost
error: timeout
{'INFO': 2, 'WARNING': 1, 'ERROR': 2}
malformed lines: 1

Source

The continue statement, break and continue statements in the Python tutorial

In this article we have used the continue statement to skip loop iterations in for and while loops, replaced nested conditions with guard clauses, skipped invalid data, and seen how continue works with nested loops, the loop else clause, and try/finally. See also Python break statement, Python control flow, and Python filter list.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.