A loop's else, and the walrus operator :=
🌍 In real life. You look for your keys in three pockets. If you find them, you stop looking. Only if you have checked every pocket without finding them do you say "I've lost my keys". That last step belongs to the search as a whole, and it happens only when the search never stopped early.
The idea in one sentence: a for or while loop can have an else: block, which runs when the loop ends by itself (it runs out of values, or its condition becomes False), and is skipped when break ends it.
Its words:
- loop else: the
else:lined up withfororwhile, not with anifinside - ends by itself: a
forruns out of values; awhilefinds its condition False - break: ends the loop early, and so skips its
else
Step by step:
- the loop checks the values one at a time
- if one of them makes it
break, the loop ends and theelseblock is skipped - if no value breaks, the loop ends by itself, and then the
elseblock runs once
Watch a search for 8 that never finds it: the values run out, and the else block runs.
Now the same loop finds 8: break ends it at once, so the else block never runs.
Why it is useful. In Lesson 7.4 the prime check needed an extra flag, is_prime = True, set to False before break, and an if after the loop to read it. A loop's else is that flag built in: reaching the else block means no divisor was found. Many people read the word as "no break".
n = 21
for d in range(2, n):
if n % d == 0:
print(n, "is not prime: it divides by", d)
break
else:
print(n, "is prime")
n = 13
for d in range(2, n):
if n % d == 0:
print(n, "is not prime: it divides by", d)
break
else:
print(n, "is prime")The walrus operator :=. Often a loop reads a value and then tests it, so the reading line appears twice: once before the loop and again at the end of it. name := value is an assignment expression: it stores the value in name and gives the value back, so you can store and test in one place. People call := the walrus operator, because it looks like a walrus lying on its side.
Below, (word := input()) != "done" reads a word, keeps it in word, and compares it with "done", all in the while line. The brackets matter: they make Python store the word first and compare afterwards.
while (word := input("Word: ")) != "done":
print(word.upper())
print("bye")Mistakes and edge cases.
- lining up
elsewith the wrong line: under anifinside the loop,elsebelongs to thatifand runs on every lap where the test is False; to belong to the loop, it must line up withfororwhile - an empty loop:
for x in []:never runs its body and never breaks, so its else does run - while-else: the else runs when the condition turns False; a
while True:loop can only end with break, so its else never runs - forgetting the walrus brackets:
word := input() != "done"stores the True or False of the comparison, not the word - using
:=as a plain line:x := 5on its own line is a SyntaxError; writex = 5; the walrus belongs inside a bigger expression
Quiz
What does this print?
for n in [2, 4, 6]: if n % 2 == 1: print("odd one:", n) break else: print("all even")What does this print?
for n in [2, 5, 6]: if n % 2 == 1: print("odd one:", n) break else: print("all even")What does this print?
for x in []: break else: print("else ran")What does this print?
count = 0 while (count := count + 1) < 4: pass print(count)This should print "not found" once, only if 7 isn't in the list. Instead it prints it for every number that isn't 7. Which line is wrong?
for n in [1, 2, 3]: if n == 7: print("found") break else: print("not found")
Coding tasks
Ask for a whole number
n(2 or more) and printprimeornot prime, like Lesson 7.4, but this time with a loop'selseinstead of a flag.Read a whole number, then look for it in
nums = [4, 8, 15, 16, 23, 42]. Printfound atand its position (counting from 0), ornot foundif it isn't there. Use a loop'selse.Keep reading words until the word is
stop. Print each word's length on its own line, then printdone. Read and test in thewhileline with the walrus operator:=.