因此,在编写一些代码来计算购物清单总数时,我编写了这段代码(在Codecademy上):
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total = total + prices[item]
value = stock[item] - 1
return value
return total
现在,当我运行它时,它没有给出错误,但它说当1个梨,苹果和香蕉在购物清单上而不是'7'时它给出答案'5'。我查看了代码,但找不到我错的地方。
答案 0 :(得分:0)
只需从for循环中删除return value
:
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
#remove item from stock
stock[item] -= 1
return total
请注意,根据输入数据,库存中没有苹果。因此,只能从购物清单中购买一个香蕉和一个橙子,总价格为5.5
:
print compute_bill(shopping_list)
5.5
stock : {'orange': 31,
'pear': 15,
'banana': 5,
'apple': 0}