Skip to main content
 首页 » 编程设计

python之这个用于计算食物账单的 python 代码有什么问题

2025年05月04日12shangdawei

我一直在上 Codecademy 的类(class),它给了我这个任务:

Define a function compute_bill that takes one argument food as input. In the function, create a variable total with an initial value of zero. For each item in the food list, add the price of that item to total. Finally, return the total.

这是我的代码:

def compute_bill(food): 
    total=0 
    for x in food: 
        total+=x 
    return total  

这是他们给我的错误:

compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +=: 'int' and 'str'

我不知道我做错了什么。

请您参考如下方法:

你没有正确阅读作业:

For each item in the food list, add the price of that item to total.

您添加的是商品本身,而不是商品的价格。

您可能有一些方法可以找到每件商品的价格,例如字典。您不能添加 'apple' 字符串,但如果苹果的价格为 0.10(10 美分),那么您可以添加 0.10 到 总计。

例如,如果您有一个名为 prices 的字典,您可以这样做:

prices = { 
    'apple': 0.10, 
    'pear': 0.15, 
    'cumquat': 0.50, 
} 
 
def compute_bill(food): 
    total = 0 
    for item in food: 
        total += prices[item] 
    return total  

请注意,我将 x 更改为 item,这是一个与您的赋值文本匹配的更具描述性的变量名称。