将项目追加到列表

时间:2020-02-18 05:10:25

标签: python list

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

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

1 个答案:

答案 0 :(得分:6)

这就是你应该做的

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

由于在循环中声明了浇头,因此每次迭代都将其初始化为空列表

相关问题