Sub topic 8
The else clause on a while loop
What you need first
This chapter assumes you can write a basic while loop and that you know how break leaves a loop early. It also assumes you are comfortable with if/else, comparison operators, and function return. The earlier chapters on loop conditions and break cover these.
By the end you should be able to:
- Say when a loop's
elseblock runs and when it does not. - Use
elseto detect that a search found nothing. - Predict which loop an
elsebelongs to in nested code. - Decide when a flag variable or a function is clearer than
else.
The rule in one sentence
A while loop can have an else block after its body. The else block runs when the loop condition becomes false. It is skipped when the loop is left by break.
n = 3
while n > 0:
print(n)
n -= 1
else:
print("condition became false")
print("after the loop")This prints 3, 2, 1, then condition became false, then after the loop. Here the else block adds nothing, because the same line placed after the loop would also run. The clause matters only when a break is possible, because break skips the else block and nothing else.
The name is confusing. It does not mean "otherwise, if the loop did not run". Read it as "if the loop finished without a break". Some Python programmers say nobreak to themselves when they read it.
How control flows
The diagram shows the three exits from a loop with an else clause.
Two details from the diagram are worth stating directly:
- The
elseblock runs at the moment the condition is checked and found false. It runs once, not on every pass. continuereturns to the condition check, so it never prevents theelseblock from running later.
The classic use: a search that can fail
A loop that looks for something has two outcomes. Either it finds the item and breaks, or it runs out of candidates. The else block is the "ran out" branch. This is the prime-number check from the plan:
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 value 2, and 2 * 2 <= 7 is true, but 7 % 2 is 1. The loop then stops, because 3 * 3 = 9 is greater than 7. The condition is false, no break happened, and the else block prints 7 is prime. For n = 9 the loop breaks at d = 3, so the else block is skipped and only 9 is not prime appears.
Without else, you would need a flag variable to remember what happened:
n = 7
d = 2
is_prime = True
while d * d <= n:
if n % d == 0:
is_prime = False
break
d += 1
if is_prime:
print(f"{n} is prime")
else:
print(f"{n} is not prime")Both versions behave the same. The else version removes one variable and one extra check. The flag version is longer, but many readers find it easier to follow. Which one you choose is a style decision, and a later section gives the criteria.
Retry loops
The same pattern fits "try up to N times, and report if every try failed". Here connect is a stand-in that succeeds from the third attempt on:
def connect(attempt):
return attempt >= 3
attempt = 1
while attempt <= 5:
if connect(attempt):
print(f"connected on attempt {attempt}")
break
attempt += 1
else:
print("gave up after 5 attempts")This prints connected on attempt 3. If you change the success test to attempt >= 9, every attempt fails, the condition attempt <= 5 becomes false, and the output is gave up after 5 attempts.
The success path and the failure path are each written once, in the place where they belong. The break marks success, and the else marks exhaustion.
What does and does not skip the else block
The rule depends on how the loop is left, so it helps to list every way out.
| How the loop ends | Does `else` run? |
|---|---|
| Condition becomes false after some passes | Yes |
| Condition is false the first time it is checked | Yes |
| `break` in the body | No |
| `return` inside the body | No, the function exits |
| An exception propagates out of the body | No |
| `continue` (followed later by a false condition) | Yes |
The second row surprises many learners:
queue = []
while queue:
print("never printed")
else:
print("else still runs")The loop body never executes, but the condition was checked and was false, so the else block runs. If you want "do something only when the loop ran at least once", else does not give you that. You need a counter or a flag.
The return row is why else combines well with functions. Here is a search function that returns an index or -1:
def index_of(values, target):
i = 0
while i < len(values):
if values[i] == target:
break
i += 1
else:
return -1
return i
print(index_of([4, 8, 15, 16], 15))
print(index_of([4, 8, 15, 16], 99))This prints 2 and then -1. When break fires, the else block is skipped and return i runs with i still pointing at the match. When the list is exhausted, the else block returns -1. Notice that i is still available after the loop, because Python loops do not create their own scope.
Which loop does the else belong to?
An else attaches to the loop that has the same indentation. In nested loops, an else aligned with the inner while belongs to the inner loop. A break inside the inner loop only affects the inner loop, and so does the else.
This program lists the primes up to 20 by running the prime check from earlier inside an outer loop:
n = 2
while n <= 20:
d = 2
while d * d <= n:
if n % d == 0:
break
d += 1
else:
print(n, end=" ")
n += 1
print()The output is 2 3 5 7 11 13 17 19. The inner break leaves only the inner loop, and its else runs when the inner loop completes. The statement n += 1 is at the outer loop's indentation, so it runs for every n, whether or not the inner loop broke.
An else aligned with the outer while would run once, after the outer condition n <= 20 became false. Moving one line of indentation changes which loop the clause belongs to and how often it runs.
Mistakes to watch for
Confusing a while-else with an if-else
This code is a common trap:
n = 0
while n < 3:
if n == 5:
break
else:
print("not five yet")
n += 1Here the else is indented under if, so it belongs to the if and runs on every pass. It has nothing to do with the loop. To attach an else to the loop, align it with while. The two mistakes look alike in a code review, so check the indentation first whenever an else seems to behave strangely.
Expecting else to mean "the loop never ran"
As shown earlier, else runs even when the body never executed. A loop with a false condition on the first check runs only its else block.
Expecting continue to cancel else
continue only skips the rest of one pass. If the loop later ends through its condition, else runs.
Using else when the failure path needs to be obvious
Many readers do not use loop else often and do not remember its meaning. If the path matters, for example in error handling or security checks, a comment helps. A function with an early return, or a named flag, may be easier for the next person to read.
When to use else, a flag, or a function
Use these criteria to choose:
| Situation | Better choice |
|---|---|
| One loop, one search, two outcomes | `else` is compact and fine |
| You need to know the result after more code has run | A flag variable, which you can store and test later |
| The search is reusable or the loop is long | Put it in a function and `return` from inside the loop |
| Several nested levels need to be left at once | A function with `return`, since `break` leaves only one loop |
| Your team rarely uses loop `else` | A flag variable, with a comment if needed |
Compare these two ways to find a pair that sums to a target. The first sets a flag. The second uses a function and returns early:
def find_pair(nums, target):
i = 0
while i < len(nums):
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return i, j
j += 1
i += 1
return None
print(find_pair([2, 7, 11, 15], 9))This prints (0, 1). No else is needed, because the function ends the moment a pair is found, and the final return None is the "not found" result. For a double loop like this one, the function is usually the cleanest design.
Summary of the rules
- The
elseblock runs once, when the condition is checked and found false. - A
breakskips it. Areturnor an exception also skips it, because control leaves the loop for good. continuedoes not skip it.- It runs even if the loop body never executed.
- It belongs to the loop at the same indentation, not to an
ifinside the body.
Exercise
What does this code print, and why? i = 0 while i < 5: i += 1 if i == 3: continue if i == 10: break else: print("else ran") print("i is", i)
Show answer
It prints "else ran" and then "i is 5". The value 3 triggers continue, which only skips the rest of that pass. The value 10 is never reached, so break never runs. The condition i < 5 eventually becomes false with no break, so the else block runs. After the loop, i is 5.
Exercise
Write a function firstnegative(values) that uses a while loop with an else clause to return the index of the first negative number in a list, or None if there is none. What does firstnegative([3, 0, -2, -5]) return, and what does first_negative([]) return?
Show answer
One solution: def firstnegative(values): i = 0 while i < len(values): if values[i] < 0: break i += 1 else: return None return i firstnegative([3, 0, -2, -5]) returns 2, because break fires at index 2 and the else block is skipped. first_negative([]) returns None, because the condition 0 < 0 is false on the first check, so the else block runs immediately.
Exercise
In the code below, how many times is "inner done" printed, and why? a = 0 while a < 3: b = 0 while b < 3: if b == a: break b += 1 else: print("inner done") a += 1
Show answer
It is printed zero times. In every pass of the outer loop, b counts up from 0 and reaches the value of a (0, 1, and 2 are each reached before b gets to 3), so the inner break fires every time. The inner else block belongs to the inner loop and is skipped whenever that loop breaks.