What is wrong with my code?


#1

def compute_bill(food):
total = 0
for food in prices:
total += prices[food]
return total

Oops, try again. compute_bill(['apple']) returned 10.5 instead of 2

Why is my code returning 10.5 and not 2?! I checked it and it seems correct lol


#2

Maybe you checked something similar, yet different.
Check the exact same thing:

data = ['apple']
print 'compute_bill({}) -> {}'.format(data, compute_bill(data))

I agree with the error message. My suggestion is to add the above, confirm that your result is incorrect, and add print statements in your function which say what it does step by step - compare with what you expect it to be doing for that input and adjust accordingly.


#3

Even i have the same problem and Im stuck at this point. pls help.


#4

try:
def compute_bill(food):
total = 0
for item in food:
total = total + food[item]
#or total += food[item]
return total

see the error?, you are using in a wrong way the 'for' loop. you type food as the argument of the function and has a creatable variable in the 'for' loop.

you can see what is doing if you type a couple of print and call the function:

def compute_bill(food):
total = 0
for food in prices:
total += prices[food]
print total
print food
print prices
return total
compute_bill(['apple'])

you'll see is adding all the keys of the dictionary.