Skip to content
scipython.com

Q4.3.7Using an assignment expression

Use the an assignment expression (the walrus operator)

(a) in a while loop to determine the smallest Fibonacci number greater than 5000;

(b) in a while loop to echo back a lower-case version of the user's input (use the input built-in function) until they enter exit.

Show solution

Here are two suggested solutions:

(a) Using an assignment expression with a tuple:

>>> t = 1, 1
>>> while (t := (t[0] + t[1], t[0])) < (5000, 0):
...     continue
... 
>>> t[0]
6765

(b) With an assignment expression involving input in a while loop:

>>> while (s := input("> ").lower()) != "exit":
...     print(s)
... 
> hello
hello
> bye
bye
> quit
quit
> :q
:q
> exit
>>>