Reputation: 13
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
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
Reputation:
It is appending the result of input("your food?:") != "q"
to the list, not your input.
Upvotes: 0
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