Home > Back-end >  True values in list
True values in list

Time:10-31

code

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)

CodePudding user response:

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)

CodePudding user response:

It is comparing input and "quit". When you enter kl and kgh, they are not equal to "quit" and food is True and it gets appended to foods. When you enter "quit" as the input, quit is equal to quit and food is False and the expression become while False so the loop breaks. Instead, do this code:

foods=[]
while True:
    food=input("what food do you like: ")
    if food=="quit":
        break
    else:
        foods.append(food)
print(foods)
  • Related