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
- Python3.14.4
- OSUbuntu 26.04 LTS
- pip25.1.1
- TimeAbout 16 min
- Reviewed23 August 2026
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.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
Before you start
-
break leaves the loop immediately
breakabandons 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 loopExpected result
body 0,body 1,body 2,breaking at 3,after the loop.Success conditionYou can count the iterations a
breakallows. -
continue skips the rest of one iteration
continueabandons 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: 5doneExpected result
odd: 1,odd: 3,odd: 5, thendone.Success conditionYou can predict which iterations produce output and which are skipped.
-
The loop else, and its one rule
Both
forandwhilemay be followed by anelseclause. The rule is one sentence:> The
elseruns unless the loop was left bybreak.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
breakhappened.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 happenedbreakingafterExpected resultThe first loop's
elseruns; the second's does not.Success conditionYou can decide whether a loop's
elseruns by looking for abreak. -
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 nobreakhappened - there was no opportunity for one.One
forover an empty list, onewhilewhose 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 iterationsExpected resultBoth
elseclauses run. Neither body did.Success conditionYou can apply the rule to a loop that never iterated.
-
The idiom the loop else exists for
Search. You loop looking for something,
breakwhen you find it, and want to do something different if you never did.Without the
elseyou 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 foundExpected result
found grace, thennot found.Success conditionYou can write a search that reports failure without a flag variable.
-
break leaves one loop, not all of them
In nested loops,
breakexits only the loop that immediately contains it. There is no labelled break and nobreak 2in 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 continuedExpected resultOne
innerline per outer iteration, each followed by the outer continuation message.Success conditionYou know how far a
breakreaches. -
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 abreakwhere 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 15Expected result
stopped at n = 5 with total 15.Success conditionYou can write a loop whose exit test sits in the middle of the body.
-
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
breakand stop counting there, part-way through the body if that is where it sits."Does the
elserun?" - only if nobreakhappened. Zero iterations still count as no break."What is wrong with this
whileloop?" - acontinueabove 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." -
forwithbreakandelse.One sentence carries most of the marks here: the loop
elseruns unless abreakhappened. Read it asnobreakand 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 ~/pyExpected resultAn empty scratch directory.
Success conditionBlock 2 is complete - the largest single area in either syllabus.
Troubleshooting
A
whileloop with acontinuein it never ends.Why: The increment is after the
continue, so it is skipped and the condition never changes.Fix:Advance the counter before the
continue, or restructure as aforloop where the advance is automatic.A loop's
elseruns when you expected it not to.Why: No
breakwas reached. Completing normally, or never iterating at all, both count as no break.Fix:Read
elseasnobreak. If you want "only when the loop actually ran", test the collection's length instead.breakonly escapes the inner of two nested loops.Why: That is all
breakdoes. Python has no labelled break.Fix:Set a flag and test it in the outer loop, raise and catch an exception, or move the inner loop into a function and
return.SyntaxError: 'break' outside loop.Why:
breakwas used in anifor a function body that is not inside a loop.Fix:Use
returnto leave a function.breakis only meaningful insidefororwhile.Output stops one line earlier than expected.
Why: The
breaksits above theprintin the body, so the final iteration is abandoned before printing.Fix:Nothing is wrong - trace the body statement by statement, not iteration by iteration.