分配的说明是:
定义一个函数compute_bill,它以一个参数food作为输入。在函数中,创建一个初始值为零的变量total。对于食品清单中的每一项,将该项目的价格相加到总数中。最后,返回总数。忽略您要支付的项目是否有库存。
请注意,您的功能应该适用于任何食物清单。
以下是我解决这个问题的尝试
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“的随机列表放进去,就像它说的那样。有人能帮帮我吗?
发布于 2017-02-17 11:35:27
您所面临的错误是因为您试图从不包含该键的字典中获取项目jok的价格。
为了避免该错误,最好检查正在检查的键是否存在,如下所示:
if item in prices:
total+= prices[item]因此,考虑到代码应该如下所示:
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'])发布于 2017-02-17 11:30:22
食物是一个列表,而不是一本字典--所以你不能通过列表中的索引以外的任何东西来查找列表中的某一项。但是没有必要重新查找项目,因为您已经在迭代它了。
你也不能在字典上迭代,所以这也需要修改
for items in prices:
if food[item]==prices[items]:应该只是
for key, val in prices.items():
if item == key:但是这仍然是没有意义的,相反,你只需要知道这个项目是否在字典中。
for item in food:
price = prices.get(item)
if price:
total+=pricehttps://stackoverflow.com/questions/42296709
复制相似问题