A Day at the Supermarket: Making a Purchase



Hello all - please may you point me towards what the issue is with my code?
The code itself appears to work, but not as it should.

My error message is: "Oops, try again. compute_bill(['apple']) returned 7.5 instead of 2"

It looks like the code is returning the price of all three items in the shopping list rather than just one at a time... any help much appreciated!

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


look at this code:

# function declaration 
def compute_bill(food):
    print food

# function call

see how the argument (shopping_list) is copied into the function parameter?

Thus, we should loop over the function parameter (food) so that our function works for any argument we supply at function call

Once you grasp this concept you might need to remove the function call, otherwise you might get in trouble with the validition


Thank you for your reply!
So sorry, have just been looking at your comment for about 20 mins but I don't think it's going in (a monday morning thing most probably!)
I see how the (shopping_list) has been copied into the function parameter, where (food) goes in the function definition... it's the looping over the function parameter bit that I think my brain is stuck on.


look at your current loop:

for food in shopping_list:

It has food as iterator, and is looping over shopping_list. By looping over shopping_list, your function will only work for one lists, not for any lists you provide as argument.

loop over food, maybe item is a good name for your iterator? since it will contains the items from the food list?

since you have the function call, you can add print statements to see what the function does at any given point


Thank you so much for the explanation - It's finally gone in.
So, I was originally asking the code to loop over just the shopping_list rather than any specific items within it?


yea, you where loop over shopping_list. This means your function only worked for on list, not any lists supplied as argument at the function call


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