我想将项目追加到列表中。但只有中间项目添加到列表中。这是我编写的代码。

while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings = []
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")

最佳答案

这是你应该做的

toppings = []
while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")


由于顶部是在循环内声明的,因此每次迭代都将其初始化为空列表

09-07 16:35