A Day at the Supermarket: Making a Purchase


#1



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

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


#2

look at this code:

# function declaration 
def compute_bill(food):
    print food

# function call
compute_bill(shopping_list)

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


#3

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.


#4

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


#5

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?


#6

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


#7

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