Making a Purchase


#1



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


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


I do not understand why I am not getting the right answer. I wonder why?


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 i in prices:
        
        total += prices[i]
    return total


#2

Hi @sebastienmercierbell,

The parameter of the compute_bill is food. Use that in this loop header instead of prices ...

    for i in prices:

Then, inside the loop, you can access prices, as you do here ...

        total += prices[i]

#3

I have the same error. I don't understand where the 10.5 came from?


#4

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

print compute_bill(stock)

Try this, it worked for me


#5

The 10.5 comes from searching through the incorrect list.

As written, your code takes the total of all the prices. That total happens to add up to 10.5. The method should be searching through the food list, not the prices list.

As stated previously, changing:

for i in prices:

to

for i in food:

should solver your problem.


#6

Glad one solution on codeacademy works. can you please explain the last line of code and how it works


#8

last one is not really required


#9

So, just for clarification, why is is it total+=prices[i] instead of, say, stocks?


#10

That is because the instructions include this ...

For each item in the food list, add the price of that item to total.

We need to add up the prices of the items rather than the number of items that are in stock.


#11