Python While Loop continue: Skip Iterations the Right Way

In a Python while loop, continue skips the rest of the current pass and jumps straight back to the condition check. The one rule to remember: update your counter before the continue, or the loop never moves forward:

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)    # 1, 2, 4, 5

Every example here ran on Python 3.12.5, plus Python 3.14 for one warning that’s new in that release.

We’ll cover skipping items, the infinite-loop trap, skipping bad data with try/except, retrying input, how continue differs from break and pass, nested loops, and what happens to a while loop’s else clause.

How continue works in a Python while loop

Here’s a packing loop that skips cancelled orders. Notice that i += 1 sits above the if, so the skip can’t stall the loop:

order_ids = [1001, 1002, 1003, 1004, 1005, 1006]
cancelled = {1002, 1005}

i = 0
while i < len(order_ids):
    order = order_ids[i]
    i += 1                      # move forward BEFORE any continue
    if order in cancelled:
        continue                # skip the packing step for this order
    print(f"Packing order {order}")

print("Checked", i, "orders")

Output:

Packing order 1001
Packing order 1003
Packing order 1004
Packing order 1006
Checked 6 orders
Command Prompt output of a Python while loop using continue to skip cancelled order numbers
Orders 1002 and 1005 never reach the print call, and the loop still checks all six orders.

When Python hits continue, it doesn’t run the lines below it in that pass. It re-checks i < len(order_ids) and starts the next pass if it’s still true. For the loop itself, start with my guide to the Python while loop.

Why does continue cause an infinite loop in a while loop?

This is the bug I see most often. If the counter update sits below the continue, the skipped pass never increments it, so the same item gets checked forever. I added a safety cap so you can run it without hanging your terminal:

orders = ["A-101", "CANCELLED", "A-103"]

i = 0
passes = 0
while i < len(orders):
    passes += 1
    if passes > 8:                       # safety cap so this demo stops
        print(f"Stuck: i is still {i} after {passes - 1} passes")
        break
    if orders[i] == "CANCELLED":
        continue                         # BUG: the i += 1 below never runs
    print("Shipping", orders[i])
    i += 1

Output:

Shipping A-101
Stuck: i is still 1 after 8 passes
Command Prompt output of a Python while loop stuck on the same index because continue skips the counter update
The first order ships, then the loop keeps landing on the cancelled order with the index never changing until the cap stops it.

Move the update above the check and the loop finishes normally:

orders = ["A-101", "CANCELLED", "A-103"]

i = 0
while i < len(orders):
    order = orders[i]
    i += 1                               # fix: update the counter first
    if order == "CANCELLED":
        continue
    print("Shipping", order)

Output:

Shipping A-101
Shipping A-103

A for loop can’t hit this bug, because it advances on its own. If you’re walking a list, that’s often the simpler choice; see for loop vs while loop in Python for when each one fits.

Skip bad records with try/except and continue

Real data is messy. Here a while loop sums payment amounts, and except ValueError plus continue sets aside anything that won’t convert instead of crashing the whole run:

payments = ["19.99", "N/A", "250.00", "", "74.5O", "1200.10"]

total = 0.0
skipped = []
i = 0
while i < len(payments):
    raw = payments[i]
    i += 1
    try:
        amount = float(raw)
    except ValueError:
        skipped.append(raw)
        continue                         # bad value: log it and move on
    total += amount
    print(f"Added ${amount:,.2f}")

print(f"Total: ${total:,.2f}")
print("Skipped:", skipped)

Output:

Added $19.99
Added $250.00
Added $1,200.10
Total: $1,470.09
Skipped: ['N/A', '', '74.5O']
Command Prompt output of a Python while loop using try/except ValueError and continue to skip bad payment values
Three valid amounts are added and the total prints in USD; N/A, the empty string and 74.5O (letter O) land in the skipped list.

I keep a skipped list rather than silently dropping rows, so I can report them later. For more on turning text into numbers, see converting a string to an integer in Python.

One related change in Python 3.14: a continue inside a finally block now raises a SyntaxWarning, because it can swallow exceptions. The code still runs:

i = 0
while i < 3:
    i += 1
    try:
        print("pass", i)
    finally:
        continue                         # allowed, but 3.14 warns about it
print("done")

Output:

C:\pyguides\ex_finally.py:7: SyntaxWarning: 'continue' in a 'finally' block
  continue                         # allowed, but 3.14 warns about it
pass 1
pass 2
pass 3
done

If you see that warning, move the continue out of the finally block and into the except branch.

Ask again until the input is valid with while True and continue

Input validation is where while True and continue shine together. Each bad answer sends the loop back to the prompt, and break only runs once a value passes every check:

# A list stands in for input() so you can run this as is.
# In a real script: raw = input("Tip amount in USD: ").strip()
typed = iter(["", "abc", "-5", "250", "12.5"])

while True:
    raw = next(typed).strip()
    print(f"Typed: {raw!r}")
    if not raw:
        print("  Empty, ask again")
        continue
    try:
        tip = float(raw)
    except ValueError:
        print("  Not a number, ask again")
        continue
    if not 0 < tip <= 200:
        print("  Must be between $0.01 and $200.00")
        continue
    break

print(f"Tip accepted: ${tip:,.2f}")

Output:

Typed: ''
  Empty, ask again
Typed: 'abc'
  Not a number, ask again
Typed: '-5'
  Must be between $0.01 and $200.00
Typed: '250'
  Must be between $0.01 and $200.00
Typed: '12.5'
Tip accepted: $12.50

In a real script you’d swap the list for input(), as the comment shows. My article on input() vs raw_input() in Python explains what input() returns, and the isdigit() string method is handy for whole-number prompts.

continue vs break vs pass in a Python while loop

These three look alike but do very different things. The same loop runs three times below, changing only the word used when n is 3:

for word in ("continue", "break", "pass"):
    seen = []
    n = 0
    while n < 5:
        n += 1
        if n == 3:
            if word == "continue":
                continue
            if word == "break":
                break
            if word == "pass":
                pass
        seen.append(n)
    print(f"{word:>8}: {seen}")

Output:

continue: [1, 2, 4, 5]
   break: [1, 2]
    pass: [1, 2, 3, 4, 5]
StatementWhat it does in a while loopResult above
continueSkips the rest of this pass, re-checks the condition3 is missing
breakLeaves the loop completelyStops after 2
passDoes nothing; the pass carries onAll five numbers

For a closer look at stopping a loop early, read Python break and continue statements.

Using continue inside nested while loops

A continue only affects the innermost loop it’s in. Below, empty bins are skipped, but each city still finishes and prints its done line:

stock = {"Dallas": [3, 0, 5], "Denver": [0, 0, 2]}
cities = list(stock)

c = 0
while c < len(cities):
    city = cities[c]
    c += 1
    bins = stock[city]
    b = 0
    while b < len(bins):
        qty = bins[b]
        b += 1
        if qty == 0:
            continue                     # skips this bin only, not the city
        print(f"{city} bin {b}: {qty} units")
    print(f"{city} done")

Output:

Dallas bin 1: 3 units
Dallas bin 3: 5 units
Dallas done
Denver bin 3: 2 units
Denver done
Command Prompt output of nested Python while loops where continue skips empty bins but not the outer city loop
Bins with zero units are skipped inside each city, and both Dallas and Denver still print their done line.

To skip the rest of an outer pass, set a flag in the inner loop and check it after the inner loop ends. Nested loops are also covered in my Python for loop tutorial.

Does continue skip the else clause of a while loop?

No. The else block of a while loop runs whenever the loop ends without break, and continue doesn’t count as a break:

def scan(label, readings):
    print(label)
    i = 0
    while i < len(readings):
        r = readings[i]
        i += 1
        if r is None:
            continue                     # missing reading: skip it
        if r > 100:
            print("  Alarm at", r)
            break
    else:
        print("  else ran: no alarm")

scan("Austin sensors", [72, None, 88, None, 95])
scan("Phoenix sensors", [98, None, 104, 99])

Output:

Austin sensors
  else ran: no alarm
Phoenix sensors
  Alarm at 104

Austin skipped two missing readings and still reached its else. Phoenix hit break at 104, so its else never ran. If you need the body to run at least once, see how to emulate a do-while loop in Python.

Want to keep practicing loops? These are good next reads:

Frequently asked questions

What does continue do in a Python while loop?

It skips the remaining lines of the current pass and goes straight back to the while condition. If the condition is still true, the next pass starts.

Why is my while loop with continue running forever?

The counter update is probably below the continue, so skipped passes never change it. Update the counter before the continue, or use a for loop.

What is the difference between continue and break?

continue skips one pass and keeps looping. break exits the loop completely and skips any else clause.

Can I use continue inside try/except in a while loop?

Yes. Putting continue in the except branch is a common way to skip a bad record and keep processing the rest.

Does continue work outside a loop?

No. Pyt