Why do I get this "Oops, try again. compute_bill(['apple']) returned 7.5 instead of 2" when everything seems fine to me. Is there a mistake? Please help


#1



https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096


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


Next step


shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!
def compute_bill(food):
    total = 0
    for food in shopping_list:
        total += prices[food]
    return total


#2

Basically what's happening here is your method is ignoring whatever is passed into it (food) and using the shopping_list you've defined at the top of your code.

Firstly, you should change your code so that your for loop references the argument you passed into your function. Secondly, I would change the second food reference to another variable name (for example, item) to prevent further confusion.


#3

The same "Oops, try again. compute_bill(['apple']) returned 7.5 instead of 2" is displayed after making the suggested change. What to do??
The link:
https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096
Here is my code.

shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!
def compute_bill(food):
    total = 0
    for item in shopping_list:
        total += prices[item]
    return total

#4

You still haven't changed the reference to shopping_list in your compute_bill() method.

Let's say for example you call compute_bill(shopping_list), which means you pass the array you defined at the top of your code into the function. That would work fine because your function makes a direct reference to shopping_list in your code.

However, let's say you created another array below it called short_shopping_list, which contained only ["banana", "orange"]. That wouldn't work because your method still references shopping_list rather than food in the for loop.

Here's another example:

sandwichOne = ["cheese", "ham"]
sandwichTwo = ["egg", "bacon"]

def printFood(sandwich):
    for food in sandwich:
        print food 

printFood(sandwichOne) # prints "cheese" and "ham" to the console

The above method works for both arrays because the for loop is using the variable sandwich that has been passed into printFood, rather than directly referencing sandwichOne or sandwichTwo


#5

Thanks a lot for clearing the issue.


#7