python - 将项目附加到列表
问题描述
我想将项目附加到列表中。但只有中间项目被添加到列表中。这是我写的代码。
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 - Python ML 模型在 docker 中给出错误的输出
- ruby-on-rails - 确认令牌 自动生成 NIL
- webots - “hoap2”控制器崩溃。在 Webot 模拟器中
- mongodb - 使用带有多个 mongos 的 mongoclient 连接到分片副本 mongo 集群
- php - 无法在codeigniter的json数组中获取索引
- java - org.json jar 中的 XML.toString(jsonObject) 正在修剪拖尾零
- twitter-bootstrap - Bootstrap-select 不适用于 Vuejs 中的动态填充选项
- laravel - 某些对象上缺少 Laravel Eloquent 关系
- c++ - 如何修复线程上的 SIGSEGV:c++ 中的 -1327498896 错误?
- r - 如何使用 R 复制数据框的每个子组的第一行?