用于分配的指令是:“进行购买”在Python教程Codecademy网站
定义一个函数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'])
我得到的错误是:
Traceback (most recent call last): File "python", line 26, in File "python", line 21, in compute_bill KeyError: 'jok'
我把随机列表与“JOK”它,因为它表示任何名单。有人可以帮我吗?