Making a purchase


#1



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


compute_bill(['apple']) returned 4 instead of 2


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 key in shopping_list:
        total += price[key]
        return total


#2

your function only works for the shopping_list, not for any lists supplied as argument when calling the function:

def compute_bill(food):
    total = 0
    for key in shopping_list:
        total += price[key]
        return total

compute_bill(['apple']) # this won't work, it should

#3

so what should I ? Please can you explain it to me.


#4

you shouldn't loop over shopping_list

when calling the function, we can supply an argument which get copied into the function parameter:

def compute_bill(food):
    print food

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

how could we use the function parameter (food) to our advantage


#5

I don't know I'm really lost


#6

do you see how arguments get copied into the function parameter? so that our function can work for multiply list? this assumes, we use loop over the function parameter, and not one fixed list


#7

so what should my code be?


#8

this is a pretty big hint, what do you think your code should be?


#9

so you use for loop on food?


#10

yes, very good :slight_smile: that solves one of the two problems in your code.


#11

thanks, so what is the second problem and how do I solve it?


#12

a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the loop will break

so for example, for shopping_list there are 3 items. However, in the first iteration of the loop, your loop will break (due to return), so only 1 of the 3 items is billed


#13

what do you mean by iteration?


#14

a loop iterates over a list, that is what i mean with iteration


#15

ok, so how do I stop the loop from breaking?


#16

how do you think? I am sorry, but i am trying to help you, but i leave thinking steps to you (so you learn more), please take some time to think about it, not just ask me


#17

I appreciate your help, it's just I am not understanding what I am doing wrong.


#18

well, you could simply place return outside of the loop so it doesn't cause the loop to break?


#19

and how do you place return outside of the loop?


#20

I have changed my code to:

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

what is wrong with my code?