定义一个函数compute_bill,它将一个参数food作为输入

时间:2017-07-29 08:45:53

标签: python-3.x

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 key in item:  
            total += item[key]  
    return (total)

这就是我所做的。但它不能正常工作。
错误:compute_bill([' apple'])导致TypeError:字符串索引必须是整数,而不是str

1 个答案:

答案 0 :(得分:0)

total += item[key]更改为prices[key]并删除for key in item: