当前位置: 动力学知识库 > 问答 > 编程问答 >

What is wrong with this python code to compute a food bill?

问题描述:

I've been doing a course on Codecademy and it gave me this task:

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.

This is my code:

def compute_bill(food):

total=0

for x in food:

total+=x

return total

and this is the error they gave me:

compute_bill(['apple']) resulted in a TypeError: unsupported operand

type(s) for +=: 'int' and 'str'

I don't know what I've done wrong.

网友答案:

You did not read your assignment properly:

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

You are adding the item itself, not the price of the item.

You presumably have some means to find the price for each item, like a dictionary. You can't add the 'apple' string, but if apples cost 0.10 (10 cents), then you can add 0.10 to total.

If you have a dictionary named prices, for example, you could just do:

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 

Note that I changed x to item, a more descriptive variable name that matches your assignment text.

网友答案:

You should sum up the prices of each food, and not the food itself. Assuming you have a dictionary of prices, your code should be something like this:

def compute_bill(food):
  total = 0
  for x in food:
    total += prices[x]
return total
网友答案:

The error is telling you: You cannot add up an integer and a string. This is because you are adding your total (an integer) and the food itself, instead of the price. You can fix this with: your_dictionary[food], instead of just food. Hope this helps!

网友答案:

This the right code, it took me along time to fix it but make sure it looks similar to this :

def compute_bill(food):
    total = 0
    for each in food:
        total += prices[each]
    return total
分享给朋友:
您可能感兴趣的文章:
随机阅读: