This code stores your favorite foods in a list, but the input turns into a bool type character. Why is this happening and how can I fix it?
foods=list()
while food := input("what food do you like?: ") != "quit":
foods.append(food)
print(foods)
This code stores your favorite foods in a list, but the input turns into a bool type character. Why is this happening and how can I fix it?
foods=list()
while food := input("what food do you like?: ") != "quit":
foods.append(food)
print(foods)
On
That happens because of the operation precedence. The expression
food := input("what food do you like?: ") != "quit"
is read as
food := (input("what food do you like?: ") != "quit")
which is what makes food a bool. You can fix it by adding parentheses:
while (food := input("what food do you like?: ")) != "quit":
foods.append(food)
It is comparing input and "quit". When you enter kl and kgh, they are not equal to "quit" and food is
Trueand it gets appended to foods. When you enter "quit" as the input, quit is equal to quit and food isFalseand the expression becomewhile Falseso the loop breaks. Instead, do this code: