Why does using an assignment expression in a loop condition store a bool value?

100 Views Asked by At

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)
2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

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)
0
bereal 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)