Sub topic 12
The Loop else Clause
This chapter assumes you can write a for loop and use break and continue, as covered in the earlier chapters. It also assumes you know that range() produces integers.
What the clause does
A for loop can have an else block. Python runs it once, after the loop ends normally. The block is skipped if the loop exits through break.
The name is misleading. It does not mean "otherwise, if the loop body did not run." A better reading is "no break happened." The clause is mainly useful for search loops: you look for something, stop when you find it, and need to act only if you never found it.
numbers = [3, 7, 12, 5]
for n in numbers:
if n % 2 == 0:
print("first even number:", n)
break
else:
print("no even numbers")This prints first even number: 12. If you change the list to [3, 7, 5], the loop finishes without a break, and the output is no even numbers.
The control flow
A prime-number search
The standard example tests each number from 2 to 9 for divisors.
for n in range(2, 10):
for d in range(2, n):
if n % d == 0:
break
else:
print(n, "is prime")The output is 2 is prime, 3 is prime, 5 is prime and 7 is prime. The else belongs to the inner for, so it lines up with that for and not with the if. When a divisor is found, break skips the else. When d runs through every value without a hit, the else prints the number.
The number 2 shows a useful edge case. range(2, 2) is empty, so the loop body never runs and no break can happen. The else block still runs. An empty iterable counts as finishing normally.
Comparing with a flag variable
Without else, you need a flag that records whether the search succeeded.
def is_prime(n):
found_divisor = False
for d in range(2, n):
if n % d == 0:
found_divisor = True
break
if not found_divisor:
return True
return FalseThe else version removes the flag and keeps the "not found" action next to the loop. When the loop sits inside a function, a return inside the loop is often clearer than either approach.
def is_prime(n):
for d in range(2, n):
if n % d == 0:
return False
return TrueUse for ... else when you need to run code after a failed search rather than return a value.
Common mistakes
- Expecting
elseto run for an empty loop only. It runs whenever there was nobreak, including after a loop that processed every item. - Misaligned indentation. If you indent
elseunder theif, it becomes an ordinaryif ... elseinside the loop, and it runs on every iteration that fails the test. - Using
continueand expecting it to skip theelse. Onlybreakdoes that. Acontinuejust moves to the next item. - Exceptions and
return. If the loop exits byreturnor by raising an exception, theelseblock does not run either.
Summary
The loop else runs when the loop finishes without break. It fits search loops where "not found" needs its own action. It also works with while loops, using the same rule.
Exercise
What does this code print, and why? for i in range(3): if i == 5: break else: print("done")
Show answer
It prints "done". The condition i == 5 is never true, because i only takes the values 0, 1 and 2. The loop therefore ends without a break, and the else block runs.
Exercise
Write a loop over the list names = ["Ada", "Grace", "Linus"] that prints the first name starting with "G" and stops. If no name starts with "G", it should print "no match". Use for ... else.
Show answer
for name in names: if name.startswith("G"): print(name) break else: print("no match")