Python 3D Academyবাংলা

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 with for or while, not with an if inside
  • ends by itself: a for runs out of values; a while finds its condition False
  • break: ends the loop early, and so skips its else

Step by step:

  1. the loop checks the values one at a time
  2. if one of them makes it break, the loop ends and the else block is skipped
  3. if no value breaks, the loop ends by itself, and then the else block 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 else with the wrong line: under an if inside the loop, else belongs to that if and runs on every lap where the test is False; to belong to the loop, it must line up with for or while
  • 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 := 5 on its own line is a SyntaxError; write x = 5; the walrus belongs inside a bigger expression

Quiz

  1. What does this print?

    for n in [2, 4, 6]:
        if n % 2 == 1:
            print("odd one:", n)
            break
    else:
        print("all even")
  2. What does this print?

    for n in [2, 5, 6]:
        if n % 2 == 1:
            print("odd one:", n)
            break
    else:
        print("all even")
  3. What does this print?

    for x in []:
        break
    else:
        print("else ran")
  4. What does this print?

    count = 0
    while (count := count + 1) < 4:
        pass
    print(count)
  5. 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

  1. Ask for a whole number n (2 or more) and print prime or not prime, like Lesson 7.4, but this time with a loop's else instead of a flag.

  2. Read a whole number, then look for it in nums = [4, 8, 15, 16, 23, 42]. Print found at and its position (counting from 0), or not found if it isn't there. Use a loop's else.

  3. Keep reading words until the word is stop. Print each word's length on its own line, then print done. Read and test in the while line with the walrus operator :=.