11.Making a Purchase explanation please


#1

My code works....But should it be total +=food[item] instead of total +=prices[item]?so it can work on any list ?
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 food:
total += prices[item]
return total


#2

It's prices because you want to add the price, right?


#3

I wish it was :stuck_out_tongue: I've changed prices to food and i get the right answer but i get an error


#4

IDK if you figured it out or not but I think you put the "return total" outside of the function.

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

#5

this code worked properly, Thanks :slightly_smiling: i have a doubt!
previously to get a keyvalue we used "for keyvalue in prices: total+=prices[keyvalue]"
But here how did prices[item] brought keyvalue from prices dict.?
can u please explain?!


#6

Hi, I think the function defines "item" as any item we might want from the prices list. So long as the list we use (e.g. "shopping_list") will match the items available in the prices dictionary, then we will be able to find prices for the items it contains.


#7

For some reason it pasted my code as a block with no indent. But if you try my code on the list stock for example. You still get the answer 10.5 even though the answer should be 53.