'Why do all values appear True when i type while loop?
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)
Solution 1:[1]
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':
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anshumaan Mishra |
