首页 > 解决方案 > 将项目附加到列表

问题描述

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

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

标签: pythonlist

解决方案


这是你应该做的

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

由于在循环内声明了 toppings,因此在每次迭代时都将其初始化为一个空列表


推荐阅读