Stuck on 11/13 "Making a Purchase"


Link to the lesson.

I've been stuck on this exercise for entirely too long. About ready to give up. I've gone back to previous exercises in the lessons, reviewing the concepts of dictionaries/for loops, and I think I get it but I just don't understand why this isn't working.

The code I've written below should work just fine (I think).

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 #sets running total to zero
    for item in food: #for every item in list
        total += food[item] #add the key value to total
    return total #then return new total

But I keep getting the error:

Oops, try again. computebill(['apple']) resulted in a TypeError: list indices must be integers, not str_

I'm not getting any errors in the interpreter so I think my syntax is okay, just not understanding why it seems to be pulling the key itself instead of the value (price).

Help please.


The problem seems to be here:

The computer is looking at the shopping_list (aka food) and trying to add a string from that list to total (an integer). To find the right total, you have to take the sum of the prices using the 'prices' dictionary in order to have an integer + an integer.
The food argument tells us what is on our shopping list, the for-loop goes through all the items on the list and should only look for the prices we need to get the correct total bill.

Hope this helps! If not, feel free to reply and I'll try to go more in-depth.


Hi ,
I am also stuck in this exercise.
I have tried the response from the topic

But the message that I got was:

Oops, try again.
compute_bill(['banana', 'apple', 'orange', 'pear']) returned 4 instead of 10.5


you need to call for prices in total:
total += prices[item]