Python KeyError:我无法弄清楚(Python的新手)

时间:2018-07-29 15:50:55

标签: keyerror

我在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)

1 个答案:

答案 0 :(得分:-1)

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