Kali
Kali

Reputation: 13

unexpected result with assignment expression

I wrote this code to try the assignment expression:

foods= list()
   while food := input("your food?:") != "q":
    foods.append(food)
else:
    print(foods)

but after input suchi and rice after running, the result was

[True, True]

Actually is did not expect this result. Can you explain??

Upvotes: 0

Views: 41

Answers (3)

Chrispresso
Chrispresso

Reputation: 4071

Order of operations. It's appending input() != 'q', which is why you're getting True. You can change your loop to this:

while (food := input("your food?:")) != "q":

Upvotes: 0

user16096234
user16096234

Reputation:

It is appending the result of input("your food?:") != "q" to the list, not your input.

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

The != operator has precedence over the := operator (in fact, every other operator has precedence over :=). So the conditional ends up as

while food := (input("your food?:") != "q"):

rather than

while (food := input("your food?:")) != "q":

Use the latter version instead and you should be fine.

Upvotes: 3

Related Questions