Why do all values appear True when i type while loop?

56 views Asked by At

I am currently learning walrus := , and when I do this coding and add to the list and then print it, a list appears with all the items True.

foods = []
while food := input("what  food do you like: ") != 'quit':
    foods.append(food)
enter code here
print(foods)
1

There are 1 answers

0
Anshumaan Mishra On

The walrus operator assignment has lower precedence as compared to the relational operators. So saying:

food := input("what  food do you like: ") != 'quit':

Evaluates as

food = <result of (input("what  food do you like: ") != 'quit')>

And until the input is quit it always returns True causing all values of food to be True and foods to be a list of all True.
You can try using:

(food := input("what  food do you like: ")) != 'quit':