Sub topic 8
The else clause on a while loop
This chapter assumes you can write a basic while loop, use break, and read if conditions and comparison operators. The topic here is the else clause that Python lets you attach to a loop.
What the clause does
A while loop can have an else block after its body. The block runs when the loop condition becomes false. It is skipped if the loop ends through break.
n = 3
while n > 0:
print(n)
n -= 1
else:
print("Condition became false")This prints 3, 2, 1, and then Condition became false. With no break in the body, the else block always runs, so here it adds nothing. The clause is only useful when the body contains a break.
The else is better read as "no break". It runs when the loop finished without being cut short.
Detecting that no break happened
Many loops search for something. If the search finds it, the loop calls break. If the loop runs out of candidates, the search failed. The else block is the natural place to handle failure.
n = 7
d = 2
while d * d <= n:
if n % d == 0:
print(f"{n} is not prime")
break
d += 1
else:
print(f"{n} is prime")For n = 7, d takes the values 2, then 3. At d = 3, d * d is 9, which is greater than 7, so the condition becomes false. No divisor was found and no break ran, so the else block prints 7 is prime.
Change n to 9 and the loop reaches d = 3, finds 9 % 3 == 0, prints 9 is not prime, and breaks. The else block is skipped.
Comparing with a flag variable
Without else, you would track the result in a separate variable.
n = 7
d = 2
found_divisor = False
while d * d <= n:
if n % d == 0:
found_divisor = True
break
d += 1
if found_divisor:
print(f"{n} is not prime")
else:
print(f"{n} is prime")Both versions behave the same. The flag version is longer, but many readers find it easier to follow. Use the else clause when it makes the code shorter and your team knows the idiom. Otherwise, a flag or a function is a fine choice.
Other ways to leave the loop
The else block is skipped only when break ends the loop. Other exits behave differently:
- A
returninside the loop leaves the whole function, so theelseblock never runs. - An exception that propagates out of the loop also skips the
elseblock. - A
continuedoes not skip theelseblock. It only moves to the next condition check, and the loop can still end normally.
i = 0
while i < 5:
i += 1
if i % 2 == 0:
continue
print(i)
else:
print("Finished without break")This prints 1, 3, 5, and then Finished without break.
If the condition is false the very first time it is checked, the body never runs, but the else block still does.
count = 0
while count > 0:
print("never printed")
else:
print("The else block still runs")Common errors
- Reading
elseas "if the loop did not run". It runs whenever there was nobreak, including after many iterations. - Indenting
elseat the wrong level. Align it withwhile, not with theifinside the body. If you indent it under theif, it becomes an ordinaryif/elseand runs on every pass. - Using
elsewhen the loop has nobreak. The block always runs, so the clause is redundant. Put the statements after the loop instead.
n = 5
while n > 0:
if n == 2:
print("Found 2")
break
n -= 1
else:
print("This else belongs to the if-less indent, and is a syntax error")The last example is invalid Python, because an else at that position has no matching if. Python raises a SyntaxError. Keep else aligned with while.
Exercise
What does this code print? n = 10 while n > 0: n -= 3 if n == 4: break else: print("no break") print("n =", n)
Show answer
It prints n = 4. The values of n are 7, 4. When n reaches 4, break runs, so the else block is skipped and only the final print executes.
Exercise
Write a loop that searches the list nums = [3, 8, 12] for the first even number using a while loop with an index. Print the number if found, or No even number if not, using the else clause.
Show answer
i = 0 while i < len(nums): if nums[i] % 2 == 0: print(nums[i]) break i += 1 else: print("No even number") For this list it prints 8.