← Home

048. Continue

Skip iterations that don't require processing

048. Continue

RAM Manager: Filtering Process Data

Aryan’s RAM manager skips system processes (pid <= 100) and zero-memory entries when computing statistics. He writes filters using nested if blocks, but the cleaner pattern is continue — which skips the rest of the loop body and moves to the next item.

His sum_positives has a real bug: it processes n == 0 (adds 0, harmless) but also processes negatives because the condition is n > 0 inside the outer loop — wait, no. The actual bug is different: it returns the total of all numbers because total += n is outside the if block (wrong indentation). A classic Python indent bug.


💡 Fun fact: Python’s mandatory indentation was inspired by ABC, a teaching language developed at CWI Amsterdam in the 1980s. Guido van Rossum worked on ABC before creating Python and kept the indentation rule because it eliminates whole classes of bugs — including the infamous 2014 “goto fail” SSL bug in Apple’s iOS where a misaligned C statement without braces silently skipped a critical security check, affecting millions of devices.

⚠️ Watch out: Python’s indentation bug is uniquely silent — total += n at the wrong indent level runs every iteration without any error. The code looks correct at a glance. This is why experienced Python developers configure their editors to show indentation guides and use linters like flake8 or pylint that can catch suspicious indentation patterns.

🤔 Think about it: continue and nested if are functionally equivalent — if n <= 0: continue; total += n does the same thing as if n > 0: total += n. So when does using continue actually make code clearer, and when does it just add an extra keyword for no benefit?

Learning objectives

  • Use continue to skip iterations matching a condition
  • Reduce nesting by using continue instead of nested if
  • Recognize indentation bugs in Python

Key concepts

  • continue
  • skip iteration
  • guard clause

Try it

Concept detail

continue skips the remaining statements in the CURRENT loop iteration and jumps to the next.

Without continue (nested if): for n in numbers: if n > 0: total += n # logic is nested one level deep

With continue (guard clause pattern): for n in numbers: if n <= 0: continue # skip invalid — inverted condition total += n # logic at top level — cleaner with many conditions

Both are functionally equivalent. Use continue when:

  • The “skip” condition is clearer to state than the “process” condition
  • You have multiple conditions that could cause a skip
  • Nesting would make the main logic harder to see

continue only affects the INNERMOST loop, just like break.

Python indentation bug — extremely common for beginners: for n in numbers: if n > 0: pass total += n # THIS IS OUTSIDE THE IF! Runs for every n.

sum_positives([1, -2, 3]) returns 2, not 4!

One wrong tab/space changes program behavior completely. This is why consistent indentation (PEP 8 recommends 4 spaces) matters.

Solution

def sum_positives(numbers):
    total = 0
    for n in numbers:
        if n <= 0:
            continue
        total += n
    return total

def clean_words(words):
    result = []
    for word in words:
        stripped = word.strip()
        if not stripped:
            continue
        result.append(stripped)
    return result

Tests

def test_sum_positives():
    assert sum_positives([1, -2, 3, 0, 4]) == 8

def test_sum_positives_not_all():
    result = sum_positives([1, -2, 3, 0, 4])
    assert result != 6, f"Got {result} — negatives and zeros are being included (indentation bug)"

def test_sum_positives_all_negative():
    assert sum_positives([-1, -2, -3]) == 0

def test_clean_words():
    result = clean_words(["hello", "  ", "world", "", "  foo  "])
    assert result == ["hello", "world", "foo"]

def test_clean_words_skips_whitespace_only():
    result = clean_words(["  ", "\t", "   "])
    assert result == [], "Whitespace-only strings should be skipped"

def test_clean_words_empty():
    assert clean_words([]) == []

def test_sum_positives_empty():
    assert sum_positives([]) == 0

Resources