CertGrid CertGrid
Concepts·Certified Entry-Level Python Programmer

Python Loop Control and else

The second half of objective 2.2. `break` leaves a loop, `continue` skips to the next iteration, and both loops accept an `else` clause that runs only if no `break` happened - a construct almost unique to Python and one PCEP asks about by name. The rule is one sentence, and this guide proves it four ways: a loop that finishes, one that breaks, one whose body never runs, and the search idiom the clause exists for.

Control Flow Guide 12 of 26 Beginner

Written against the versions above. Unchanged since Python 3.0, and `while`/`for` have accepted an `else` clause since Python 1. Nothing here is version-sensitive.

One machine, and any shell with Python 3 will do - these exams test the language, not a distribution.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSPython 3.14.4 - the only machine this path needs2 Core4 GB50 GB

Before you start

  1. break leaves the loop immediately

    break abandons the loop at once. The rest of the body does not run, no further iterations happen, and execution continues after the loop.

    The loop below would run ten times. Count how many lines it actually prints.

    bash Example session
    cat > ~/py/breakdemo.py <<'PY'for i in range(10):    if i == 3:        print("breaking at", i)        break    print("body", i)print("after the loop")PYpython3 ~/py/breakdemo.pybody 0body 1body 2breaking at 3after the loop

    Expected resultbody 0, body 1, body 2, breaking at 3, after the loop.

    Success conditionYou can count the iterations a break allows.

  2. continue skips the rest of one iteration

    continue abandons the current iteration and goes straight to the next one. The loop itself carries on.

    bash Example session
    cat > ~/py/continuedemo.py <<'PY'for i in range(6):    if i % 2 == 0:        continue    print("odd:", i)print("done")PYpython3 ~/py/continuedemo.pyodd: 1odd: 3odd: 5done

    Expected resultodd: 1, odd: 3, odd: 5, then done.

    Success conditionYou can predict which iterations produce output and which are skipped.

  3. The loop else, and its one rule

    Both for and while may be followed by an else clause. The rule is one sentence:

    > The else runs unless the loop was left by break.

    That is the whole thing. It is not "if the loop ran", and it is not "if the condition became false" - it is purely about whether a break happened.

    Two loops below: one finishes, one breaks.

    bash Example session
    cat > ~/py/loopelse.py <<'PY'for i in range(3):    print("body", i)else:    print("for-else ran because no break happened") for i in range(3):    if i == 1:        print("breaking")        breakelse:    print("this line never prints")print("after")PYpython3 ~/py/loopelse.pybody 0body 1body 2for-else ran because no break happenedbreakingafter

    Expected resultThe first loop's else runs; the second's does not.

    Success conditionYou can decide whether a loop's else runs by looking for a break.

  4. The else runs even when the body never does

    This is where most explanations get it wrong. A loop that iterates zero times still runs its else, because no break happened - there was no opportunity for one.

    One for over an empty list, one while whose condition was false from the start.

    bash Example session
    cat > ~/py/elseempty.py <<'PY'for i in []:    print("never")else:    print("else ran after zero iterations") n = 10while n < 3:    print("never")else:    print("while-else ran after zero iterations")PYpython3 ~/py/elseempty.pyelse ran after zero iterationswhile-else ran after zero iterations

    Expected resultBoth else clauses run. Neither body did.

    Success conditionYou can apply the rule to a loop that never iterated.

  5. The idiom the loop else exists for

    Search. You loop looking for something, break when you find it, and want to do something different if you never did.

    Without the else you need a flag variable set inside the loop and tested after it. With it, the two outcomes sit next to each other.

    bash Example session
    cat > ~/py/search.py <<'PY'names = ["ada", "grace", "alan"] for name in names:    if name == "grace":        print("found", name)        breakelse:    print("not found") for name in names:    if name == "linus":        print("found", name)        breakelse:    print("not found")PYpython3 ~/py/search.pyfound gracenot found

    Expected resultfound grace, then not found.

    Success conditionYou can write a search that reports failure without a flag variable.

  6. break leaves one loop, not all of them

    In nested loops, break exits only the loop that immediately contains it. There is no labelled break and no break 2 in Python.

    bash Example session
    cat > ~/py/nestedbreak.py <<'PY'for i in range(3):    for j in range(5):        if j == 1:            break        print("inner", i, j)    print("outer iteration", i, "continued")PYpython3 ~/py/nestedbreak.pyinner 0 0outer iteration 0 continuedinner 1 0outer iteration 1 continuedinner 2 0outer iteration 2 continued

    Expected resultOne inner line per outer iteration, each followed by the outer continuation message.

    Success conditionYou know how far a break reaches.

  7. while True, and why it is not a bad habit

    Python has no do-while, so the standard way to guarantee at least one pass is while True: with a break where the exit condition belongs. It is idiomatic rather than a hack.

    bash Example session
    cat > ~/py/whiletrue.py <<'PY'total = 0n = 1while True:    total += n    if total > 10:        break    n += 1print("stopped at n =", n, "with total", total)PYpython3 ~/py/whiletrue.pystopped at n = 5 with total 15

    Expected resultstopped at n = 5 with total 15.

    Success conditionYou can write a loop whose exit test sits in the middle of the body.

  8. What the exam does with these

    This half of objective 2.2 produces its own recognisable questions:

    "How many lines does this print?" - find the break and stop counting there, part-way through the body if that is where it sits.

    "Does the else run?" - only if no break happened. Zero iterations still count as no break.

    "What is wrong with this while loop?" - a continue above the increment, making it infinite.

    "How do you break out of two loops?" - you cannot, directly. Flag, exception, or a function.

    "Rewrite this search without a flag variable." - for with break and else.

    One sentence carries most of the marks here: the loop else runs unless a break happened. Read it as nobreak and the zero-iteration case stops being surprising.

    That completes PCEP block 2 - 29% of the exam, two objectives, three guides. guide 13 starts block 3.

    bash
    rm -f ~/py/breakdemo.py ~/py/continuedemo.py ~/py/loopelse.py ~/py/elseempty.py ~/py/search.py ~/py/nestedbreak.py ~/py/whiletrue.py && ls -A ~/py

    Expected resultAn empty scratch directory.

    Success conditionBlock 2 is complete - the largest single area in either syllabus.

Troubleshooting

Official sources