11. Making a Purchase


#1


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

The code for sure is correct, but codecademy returns the error. Can you, please, assist why I'm getting error: "list indices must be integers, not str"


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 += food[item]
          print item, ":", food[item]
     print "Total:", total
     return total

compute_bill(prices)


#2

the function is designed to take a list as input, when you call the function:

compute_bill(prices)

you pass a dictionary, try using the shopping_list (quit useful to calculate the total cost of your shopping)

edit, okay, because you misunderstood that food will be a list of items you are going to buy, this two lines:

total += food[item]
print item, ":", food[item]

are also wrong, you need to add the price of item you are going to buy, you can use item as key to get the value from the prices dictionary.

if you want to print the item, you can just do print item since item will hold the item you are going to buy


#3

I think there is another one reason. I've removed print from code and the error is the same:
Now function looks like that:
def compute_bill(food):
total = 0
for item in food:
total += food[item]
return total

But I get the same error: "Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str"

If I run my code in normal one interpreter it works perfect, without any error or even warning


#4

the question is, what is food (the function parameter)? When the exercise calls your function it passes a list as argument, so food will hold a list.

Then look at what you add to total:

total += food[item]

food[item]? list can only be access by indexes, not by keys like dictionary's can. you need to add the price of the item, which you can get from the prices dictionary


#6

Thank you so much. I understood my mistake. It has to be something like that:

def compute_bill(food):
    total = 0
    for i in food:
        if stock[i] > 0:
            total += prices[i]
            stock[i] -= 1
        print "Total:", total, "\n"
    return total

#7