
Code
The Walrus :=
:= looks like a walrus face, sideways. It assigns a value and
hands it back in one step. So you can use it inside a bigger
expression:
if (n := len(cargo)) > 10:
print(f"Too heavy: {n} crates")
Without the walrus you'd either call len twice or need an extra line.
It shines in two places:
Loops that read until a stop signal. next(it, default) returns the
next item from an iterator, or default when it runs out:
it = iter(["north", "east", "STOP", "west"])
while (step := next(it, "STOP")) != "STOP":
print(step) # north, east
Comprehensions that need a computed value twice:
scores = [(w, s) for w in words if (s := score(w)) > 5]
Always wrap a walrus expression in parentheses, as above.
Pip tip: use the walrus only when it makes code clearer, not just shorter.
Assignment
Use := in both functions:
long_words(words, min_len)returns a list of(word, length)tuples for the words whose length is at leastmin_len. Compute each length only once, with a walrus inside a comprehension.collect(lines)returns the lines up to (but not including) the first"END". If there's no"END", return them all. Use awhileloop with:=andnext(it, "END").
Use := in both functions:
long_words(words, min_len)returns a list of(word, length)tuples for the words whose length is at leastmin_len. Compute each length only once, with a walrus inside a comprehension.collect(lines)returns the lines up to (but not including) the first"END". If there's no"END", return them all. Use awhileloop with:=andnext(it, "END").
main.py Python sleeping
Press Run to try your code, then Check to test it.