Lesson 4 of 5 · Control Flow · 3 min read · Updated

break, continue, pass and loop else

Leaving a loop early, skipping a turn, doing nothing on purpose, and knowing a search failed.

python
for n in range(1, 10):
    if n == 5:
        break
    print(n, end=" ")
print()

for n in range(1, 10):
    if n % 2 == 0:
        continue
    print(n, end=" ")
print()
Output
1 2 3 4
1 3 5 7 9
  • break leaves the loop completely. Nothing after it in the loop runs again.
  • continue skips the rest of this turn and moves on to the next item.

The loop else

python
for n in [9, 7]:
    for d in range(2, n):
        if n % d == 0:
            print(n, "is not prime, divisible by", d)
            break
    else:
        print(n, "is prime")
Output
9 is not prime, divisible by 3
7 is prime

A loop can have an else. It runs only when the loop finished without a break — which, in a search, means "not found". Read it as "no break". Without it you would need an extra flag variable.

Warning

Mind the indentation: this else lines up with for, not with if. Indent it one level further and it becomes the if's else, running on every non-matching number.

pass: an empty placeholder

python
for student in ["Arun", "Bala"]:
    pass  # TODO: send report cards
print("Done")
Output
Done

Python does not allow an empty block, so pass fills the gap and does nothing. Use it while sketching a program: the structure runs now, the details come later.

Loops inside loops

python
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end="\t")
    print()
Output
1	2	3
2	4	6
3	6	9

Note

The inner loop runs completely for each turn of the outer one: 3 × 3 = 9 prints. A break inside the inner loop leaves only the inner loop — the outer one carries on.

When does a for loop's else block run?

Try this now

  1. Keep asking for a password until the user types "open", then print "Welcome" — use while True and break.
  2. Print every number from 1 to 30 except multiples of 3, using continue.
  3. Print a right-angled triangle of stars five rows tall with nested loops.

Create a free account to save your progress, or sign in.