gpt4 book ai didi

python - 将项目附加到列表

转载 作者:行者123 更新时间:2023-12-03 20:02:30 25 4
gpt4 key购买 nike

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

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

因为 toppings 是在循环内声明的,所以它在每次迭代时都被初始化为一个空列表

关于python - 将项目附加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60274115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com