runtime
24 / 250
lesson 24 Loops & Iteration · beginner

Stop early, or skip one

break leaves the loop the moment you have your answer. continue skips the rest of this pass and moves on to the next.

You'll be able to
  • Stop a loop with break as soon as the answer is known
  • Skip values you don't want with continue
  • Use while True with a break when the stop is decided inside the loop
The idea

Often you can stop before the end. Looking for the first bad character in a PIN? Once you've found it, the rest doesn't matter. Other times one value should simply be skipped: a blank line in a stream of barcodes.

  • break leaves the loop immediately. No more passes run, and the program continues at the first line after the loop.
  • continue ends this pass only. The loop goes straight on to the next character, number or test.

Both almost always sit inside an if, because you only want to stop or skip in some cases.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Keep the order id, drop the parcel number
ref = "O104839-2"
order = ""
for ch in ref:
    if ch == "-":
        break
    order = order + ch
print("Order:", order)

while True: is a loop whose test can never be false. It looks endless, but a break inside it ends it. Use it when the decision to stop can only be made in the middle of a pass, after reading a line, for example.

example-2.py · Scan barcodes until done
scanned = 0
while True:
    code = input()
    if code == "done":
        break
    if code == "":
        continue
    scanned += 1
    print("Scanned", code)
print("Total scanned:", scanned)

When to use them: break when the answer is known before the end (the first match, a stop word); continue when some values should be ignored and the rest handled normally.

Mistakes to avoid:

  • continue in a while loop before the line that moves it along (n += 1). The skipped pass never changes n, so the loop never ends.
  • Lines after break in the same block never run. Do what has to be done before breaking.
  • break is not continue: one stops the whole loop, the other only this pass.
Review
  • break leaves the loop at once; the line after the loop runs next.
  • continue skips the rest of this pass; in a while loop, make sure the loop still moves on.
  • while True with a break stops in the middle of a pass. Next: a loop inside a loop.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Stop early, or skip one — Loops & Iteration · Runtime