首页 > 解决方案 > 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)

标签: keyerror

解决方案


我认为您在滥用 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))


推荐阅读