keyerror - Python KeyError:我想不通(python 新手)
问题描述
我在初学者 python 课程中,我们正在创建一个杂货清单脚本。我的脚本在该行给了我一个关键错误:
item_total = int(grocery_history[y].get('number')) * float(grocery_history[y].get('price')).
我也认为最后几个打印语句也是错误的。
grocery_item = {}
grocery_history = grocery_item
x = 0
isStopped = False
while not isStopped:
item_name = input("Item name:\n")
quantity = input("Quantity purchased:\n")
cost = input("Price per item:\n")
grocery_item['name'] = item_name
grocery_item['number'] = int(quantity)
grocery_item['price'] = float(cost)
grocery_history[x] = grocery_item.copy()
exit = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
if exit == 'q':
isStopped = True
else:
x += 1
grand_total = float(0.00)
for y in range(0, len(grocery_history) - 1):
item_total = int(grocery_history[y].get('number')) * float(grocery_history[y].get('price'))
grand_total = float(grand_total) + float(item_total)
print("%d %s @ $%.2f ea $%.2f" %(grocery_history[y]['number'], str(grocery_history[y]['name']), float(grocery_history[y]['price']), float(item_total)))
item_total = 0
finalmessage = ("Grand Total: ${:,.2f}".format(grand_total))
print(finalmessage)
解决方案
我认为您在滥用 Python 字典和列表。该变量grocery_history
可以是一个存储杂货的列表(对吗?),而不是像grocery_item
确实存储键值对的字典,因此您的代码可以像这样结束:
grocery_item = {}
grocery_history = []
isStopped = False
while not isStopped:
item_name = input("Item name:\n")
quantity = input("Quantity purchased:\n")
cost = input("Price per item:\n")
grocery_item['name'] = item_name
grocery_item['number'] = int(quantity)
grocery_item['price'] = float(cost)
grocery_history.append(grocery_item.copy())
exit = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
if exit == 'q':
isStopped = True
grand_total = float(0.00)
for y in range(0, len(grocery_history)):
item_total = int(grocery_history[y].get('number')) * float(grocery_history[y].get('price'))
grand_total = float(grand_total) + float(item_total)
print("%d %s @ $%.2f ea $%.2f" % (
grocery_history[y]['number'], str(grocery_history[y]['name']), float(grocery_history[y]['price']), float(item_total)))
item_total = 0
finalmessage = ("Grand Total: ${:,.2f}".format(grand_total))
print(finalmessage)
注意:该range
函数不包含第二个参数,因此循环一直持续到列表的最后一个元素range
应该被构建range(0, len(grocery_history))
。
推荐阅读
- ckeditor4.x - 清理从 CKEditor getData() 方法接收到的 HTML 数据 [ckeditor]
- r - 错误:XML 内容似乎不是 XML
- windows - 在某些条件下批量重命名
- javascript - SocketIO 服务器不处理来自客户端的触发事件
- php - 找不到类“OSRef”
- r - 从R中数据框中的单元格中提取数字字符
- php - 使用 MySql 数据库无法通过 Android 登录到 PHP?
- angular - 对于大部分相似但地方不同的组件,Angular 的最佳实践是什么?
- docker - golang docker build for linux
- swift - 滚动后 Tableview 部分展开折叠更新