Search code examples
pythonpython-assignment-expression

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


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)

Solution

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