首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python教程中的“购买”

Python教程中的“购买”
EN

Stack Overflow用户
提问于 2017-02-17 11:24:24
回答 2查看 1.2K关注 0票数 0

分配的说明是:

定义一个函数compute_bill,它以一个参数food作为输入。在函数中,创建一个初始值为零的变量total。对于食品清单中的每一项,将该项目的价格相加到总数中。最后,返回总数。忽略您要支付的项目是否有库存。

请注意,您的功能应该适用于任何食物清单。

以下是我解决这个问题的尝试

代码语言:javascript
复制
shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
def compute_bill(food):
    total=0
    for item in food:
        for items in prices:
         if food[item]==prices[items]:
            print prices[item]
            total+=prices[item]
         else:
            print 'not found'
    return total
compute_bill(['apple', 'jok'])

我得到的错误是:

回溯(最近一次调用):文件"python",第26行,文件"python",第21行,compute_bill KeyError:'jok‘

我把一个"jok“的随机列表放进去,就像它说的那样。有人能帮帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-17 11:35:27

您所面临的错误是因为您试图从不包含该键的字典中获取项目jok的价格。

为了避免该错误,最好检查正在检查的键是否存在,如下所示:

代码语言:javascript
复制
if item in prices:
            total+= prices[item]

因此,考虑到代码应该如下所示:

代码语言:javascript
复制
shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
def compute_bill(food):
    # Set total variable to 0
    total=0
    # Loop over every item in food list to calculate price
    for item in food:
        # Check that the item in the food list really exists in the prices
        # dicionary
        if item in prices:
            # The item really exists, so we can get it's price and add to total
            total+= prices[item]
    print total
compute_bill(['apple', 'jok', 'test', 'banana'])
票数 1
EN

Stack Overflow用户

发布于 2017-02-17 11:30:22

食物是一个列表,而不是一本字典--所以你不能通过列表中的索引以外的任何东西来查找列表中的某一项。但是没有必要重新查找项目,因为您已经在迭代它了。

你也不能在字典上迭代,所以这也需要修改

代码语言:javascript
复制
for items in prices:
 if food[item]==prices[items]:

应该只是

代码语言:javascript
复制
for key, val in prices.items():
    if item == key:

但是这仍然是没有意义的,相反,你只需要知道这个项目是否在字典中。

代码语言:javascript
复制
for item in food:
    price = prices.get(item)
    if price: 
        total+=price
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42296709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档