【发布时间】:2018-07-29 15:50:55
【问题描述】:
我正在上 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)
【问题讨论】:
-
KeyError 表示在字典中找不到该键,例如
days_of_week["potato"]。我建议您首先将长线分成单独的步骤。您将获得更具体的错误位置。然后,在该行之前打印字典和键 - 这将使调试更容易。
标签: keyerror