# Error in "Making a Purchase"

#1

``````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 food in shopping_list:
total = total + prices[food]

print compute_bill(shopping_list)``````

I'm having trouble with this code. It keeps giving me the "Oops, try again. compute_bill(['apple']) returned 4 instead of 2" error and I don't understand why. Can someone help me with this?

#2

lets add a second function call:

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

print compute_bill(shopping_list)
print compute_bill(['apple'])``````

your function should calculate the correct total for both your shopping_list and other lists (in this case a list containing an apple)

we can add many more function calls, giving a different list, all should work. The trick is in parameter and argument of the function and function call

#3

It's still giving me the same error.

#4

can i see an updated version of your code?

#5

change "shopping_list" to "food". Food is the variable that is relevant to the function, "shopping_list" is only the value of food. Then delete "return total" within the for loop. You updated the total in the previous line and only want to return the total once you've completed the loop.

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

#6

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

print compute_bill(shopping_list)
print compute_bill(['apple'])
print compute_bill(['banana'])
print compute_bill(['orange'])``````

#7

for all this functions calls, the same result is printed? The products clearly have different prices, so this shouldn't happen.

the problem is in your loop:

``for food in shopping_list:``

shopping_list causes your function to only work for one list, loop over the function parameter (food) instead, so that your function works for all arguments supplied at function call

#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.