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:
total+= item
return total
我知道已经有解决这个问题的方法,但我无法在我的程序中应用它们。我正在从codecademy学习python,在这个程序中,我收到此错误。如果有人能彻底解释我相同的解决方案,我将不胜感激.thanx
这个特定练习中的说明不清楚。你基本上是在向 int 添加一个字符串,这就是你收到此错误的原因。运行下面给出的代码,它将解决您的问题。
def compute_bill(food):
total = 0
for item in food:
total = total + prices[item]
return total
上面给出的代码片段基本上是通过我们在上一个练习中创建的价格字典。每个键对应于一个存储为 int 或 float 的价格,这就是为什么您在使用上述代码时不会收到错误的原因。
您使用的是字典,循环遍历字典只会生成键。
当您像在for item in food
中那样循环遍历字典时,您实际上只是在循环字典键。因此,您需要使用键来访问要添加到总数的dict
中的值。
编辑:抱歉没有意识到您特别不想要解决方案,因此将其删除。