【发布时间】:2018-07-27 12:33:47
【问题描述】:
我有一个家庭作业,要写一个简单的购物清单,这个脚本应该可以:
接受用户输入的变量,例如项目名称、数量和项目成本
使用从用户那里收集的信息,创建一个字典条目并将其添加到名为grocery_history 的列表中
按以下格式打印出所有输入的项目:变量→数字名称价格item_total
最后输出所有物品的总成本
这是我的代码:
grocery_item = {}
grocery_history=[{}]
stop = 'go'
item_name = input("Item name:")
quantity = input("Quantity purchased:")
cost = input("Price per item:")
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)
cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
while cont != 'q':
item_name = input("Item name:")
quantity = input("Quantity purchased:")
cost = input("Price per item:")
cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)
grand_total = []
number = grocery_history[quantity]
price = grocery_history[cost]
for grocery_history in grocery_item:
item_total = int(number)*float(price)
grand_total.append(item_total)
print(grocery_history[number][name] + "@" [price]:.2f + "ea'.format(**grocery_item)")
item_total = 0
print ("Grand total:" + str(grand_total))
在我的number = grocery_history[quantity]
价格 = 杂货历史[成本]statement I get aKey Error 2`,我不知道为什么,密钥应该存在,但也许它们没有被正确添加到列表中。
任何帮助将不胜感激,如果您需要更多详细信息,请告诉我,我会编辑它们。
【问题讨论】:
-
看来
grocery_history是一个列表,而不是字典。 -
您正在尝试使用键 (str) 访问列表。它不能工作。
标签: python list dictionary