Another question about A Day at the Supermarket #11


#1




I receive the following error:
compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str


I'm not sure where there are any strings in my function. There is also another error that mentions the value being returned is not correct, but as you can see I havent even defined the food list yet. I dont know where those values are coming from.


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


#2

f is a string which cannot be used to access elements of a list. food[f] is raising the error.

n = prices[f]

Since prices is a dictionary with arbitrary indices, f as a string points to the key.


#3

I just followed your recommendation and updated to the following:

total = 0
for f in food:
total = total + prices[f]
return total

This gave me the following: compute_bill(['banana', 'apple', 'orange', 'pear']) returned 4 instead of 10.5


#4

Ok, I just realized I needed to move the return statement to the left so it was outside the loop.

Thanks for the help!


#5

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