Walrus in a while loop and an if
Move "stop" to the front of the list and run it: the loop body never runs. Change the 10 to 25 and watch the if branch switch off.
The walrus operator := assigns a value to a name inside an expression, so you can test a value and keep it in one step. It shortens loops that read until a stop signal and filters that need a computed value twice, and it is not worth using when it makes a line harder to read.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
With inbox = ["a", "b", "end", "c"], use a walrus loop with pop(0) to print each message until "end". Print a then b.
Use if (n := len("hello world")) > 5: to print Long text: 11.
Using a comprehension with a walrus, collect the squares greater than 20 from [2, 5, 3, 6] and print [25, 36].
Explain it without notes
What does the walrus operator do, and how is it different from =?
Show a loop that reads until a stop value, with and without :=.
Why does a name set with := inside an if still exist after the if?
When should you avoid the walrus operator?
Expected output
got hello
got world
left in inbox: ['ignored']
20 characters is too long