Skip to content
aviral gupta

// B2.3 · ~25 min · Beginner

break, continue, pass and else on loops

After this lesson you can stop a loop early with break, skip a round with continue, use else on a loop to handle "nothing found", and hold a place with pass.

Lesson 3 of 5 in B2 Control flow

You will be able to

  • Stop a loop early with break, and skip to the next round with continue
  • Use else on a for or while loop to run code only when no break happened
  • Know that break leaves only the innermost loop, and use pass where a block needs a statement
  1. Warm-up · Activity 1 of 7

    Warm-up from B2.2: what does this print?

    print(list(range(1, 10, 4)))
  2. Predict · Activity 2 of 7

    Predict before you read on: what does this print?

    for n in [3, 8, 5, 12, 7]:
        if n > 10:
            break
        print(n, end=" ")
  3. Practice · Activity 3 of 7

    Fill in the keyword so that the loop skips multiples of 3 but keeps going: it should print 1 2 4 5 7.

    for n in range(1, 8):
        if n % 3 == 0:
            ____
        print(n, end=" ")
  4. Practice · Activity 4 of 7

    The else is part of the for loop. What does this print?

    for drink in ["tea", "milk", "juice"]:
        if drink == "coffee":
            print("found")
            break
    else:
        print("not found")
  5. Practice · Activity 5 of 7

    Match each statement to what it does.

  6. Brain teaser · Activity 6 of 7

    Brain teaser. A loop inside a loop. What does this print?

    count = 0
    for i in range(3):
        for j in range(3):
            if j == 1:
                break
            count = count + 1
    print(count)
  7. Apply · Activity 7 of 7

    Mini-task. Write a guessing game: the secret number is 7, and the player has 5 guesses, each read with int(input()). Print higher or lower after a wrong guess, and correct when it is right, which ends the game. If all 5 guesses are wrong, print out of guesses. Use break and else on the loop.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

Adding up a day’s orders

A shop’s order list uses two markers: -1 is a cancelled order, and 0 marks the end of the day. The program skips cancelled orders with continue, stops at the end marker with break, and warns in the loop’s else if the marker is missing. A second loop searches for a large order and reports when there is none. Change the list and run it again.

main.py

# -1 is a cancelled order, 0 marks the end of the day.
orders = [120, -1, 45, 300, -1, 80, 0, 999]

total = 0
count = 0
for amount in orders:
    if amount == -1:
        continue  # cancelled: go on with the next order
    if amount == 0:
        print("End of day reached")
        break  # 999 is never read
    total = total + amount
    count = count + 1
else:
    print("Warning: no end-of-day marker")

print("Orders:", count, "Total:", total)

# Is there an order over 250? else answers "no".
for amount in orders:
    if amount > 250:
        print("Large order:", amount)
        break
else:
    print("No large orders")

Run it with

python main.py

Output

End of day reached
Orders: 4 Total: 545
Large order: 300
  • continue skips the two -1 entries, so they are neither counted nor added.
  • break at 0 ends the first loop, so its else does not print the warning.
  • The second loop stops at the first large order, 300; 999 is never checked.
  • Remove the 0 from the list and the warning appears, and 999 is added to the total.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Exercises

Exercise 1 of 2

Add numbers until done

The program reads lines until the user types done. Every other line is a whole number, except that empty lines are skipped. Print the sum of the numbers. Use while True: with break for done and continue for an empty line. For 5, 10 and done it prints 15.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    Inside while True:, read one line per round and decide what to do with it.

  2. Hint 2

    Check for done first and break. Then check for an empty line and continue, before int(line) is ever called.

  3. Hint 3

    if line == "done": break, then if line == "": continue, then total = total + int(line).

Show a solution

One way to solve it. Yours can look different and still pass the checks.

total = 0

while True:
    line = input()
    if line == "done":
        break
    if line == "":
        continue
    total = total + int(line)

print(total)
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

total = 0

while True:
    line = input()
    # Stop at "done"; skip empty lines; add the rest.
    break

print(total)

test_main.py

from learnrun import run_main


def total_for(lines):
    return run_main(lines).strip()


def test_two_numbers():
    """5 and 10 add up to 15"""
    got = total_for("5\n10\ndone\n")
    assert got == "15", f"for 5, 10, done the program printed {got!r}, expected '15'"


def test_done_first():
    """done straight away prints 0"""
    got = total_for("done\n")
    assert got == "0", f"for done alone the program printed {got!r}, expected '0'"


def test_empty_lines_skipped():
    """Empty lines are skipped"""
    got = total_for("3\n\n4\n\ndone\n")
    assert got == "7", f"for 3, empty, 4, empty, done the program printed {got!r}, expected '7'"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Exercise 2 of 2

Prime or not

The program reads a whole number n of at least 2. Try every divisor from 2 to n - 1. At the first one that divides n, print divisible by and the divisor, such as divisible by 3, and stop. If none does, print prime, using else on the for loop.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    for d in range(2, n): tries every divisor; n % d == 0 means d divides n.

  2. Hint 2

    After printing the divisor, break, so only the smallest one is reported.

  3. Hint 3

    Write else: print("prime") at the same indentation as for, not as the if.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

n = int(input())

for d in range(2, n):
    if n % d == 0:
        print("divisible by", d)
        break
else:
    print("prime")
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

n = int(input())

# Try the divisors 2 to n - 1.
print("prime")

test_main.py

from learnrun import run_main


def check(n):
    return run_main(f"{n}\n").strip()


def test_prime():
    """7 and 2 are prime"""
    got = check(7), check(2)
    assert got == ("prime", "prime"), f"for 7 and 2 the program printed {got!r}, expected ('prime', 'prime')"


def test_first_divisor():
    """9 is divisible by 3"""
    got = check(9)
    assert got == "divisible by 3", f"for 9 the program printed {got!r}, expected 'divisible by 3'"


def test_smallest_divisor_only():
    """12 reports only its smallest divisor, 2"""
    got = check(12)
    assert got == "divisible by 2", f"for 12 the program printed {got!r}, expected only 'divisible by 2' (did you break?)"


def test_larger():
    """91 is divisible by 7"""
    got = check(91)
    assert got == "divisible by 7", f"for 91 the program printed {got!r}, expected 'divisible by 7'"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Common mistakes

break outside a loop

x = 5
if x > 3:
    break

What Python prints

SyntaxError: 'break' outside loop

Why, and the fix

break and continue only make sense inside a for or while loop. An if on its own is not a loop, so there is nothing to break out of. If you wanted to skip the rest of the if, restructure it with else.

An empty loop body

for n in range(3):

print("done")

What Python prints

IndentationError: expected an indented block after 'for' statement on line 1

Why, and the fix

Every loop, if and else needs at least one indented statement. When the body is still to be written, put pass there: for n in range(3):, then pass indented under it. Python then runs the file and the loop simply does nothing.

continue that slipped out of the loop

for n in range(3):
    print(n)
if n == 2:
    continue

What Python prints

SyntaxError: 'continue' not properly in loop

Why, and the fix

The if is not indented under for, so it runs after the loop and its continue is outside any loop. Indentation decides what is inside the loop: indent the if by four spaces to make it part of the loop body.

Python in the browser: Pyodide 314.0.7, MPL-2.0. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

break stops, continue skips

break ends the loop at once: Python jumps to the first line after the loop, and the rest of the items are never looked at. continue ends only the current round: the rest of the body is skipped and the loop goes on with the next item, or checks its while condition again. Both usually sit inside an if. A common shape is while True: with a break when the work is done, for loops that cannot know their end in advance, such as reading input until the user types quit.

else on a loop means "no break happened"

A for or while loop can have an else block, written at the same indentation as the loop. It runs when the loop ends normally: a for loop has used every item, or a while condition has become false. When break ends the loop, else is skipped. That makes searches short: break when you find the item, and put "not found" in the else. Read it as "if no break". It belongs to the loop, not to an if inside the loop.

Nested loops and pass

break and continue act on the innermost loop they are in. In a loop inside a loop, break ends the inner loop, and the outer loop carries on with its next round. Python needs at least one statement in every block. When you have nothing to do yet, for example in a branch you will write later, pass is a statement that does nothing. Unlike continue, pass does not skip the rest of the loop body: the lines after it still run.

Sources

Last reviewed September 29, 2026