【问题标题】:Python KeyError: I can't figure it out (new to python)Python KeyError:我想不通(python 新手)
【发布时间】: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


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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2017-01-22
    • 1970-01-01
    • 2015-04-12
    • 2022-01-21
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多