Making a purchase


#1

This is my code!:
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 food:
total += food[i]
return total

print compute_bill(['apple'])

And this is what it responds with: Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str

I am not sure where I am going wrong, someone please help!


#2

here:

total += food[i]

food is a list, and i is a item/product (for example 'apple'), you can't access lists by string. What do you want to add to total? The price of the product/item, right? How could this be achieved?


#4

You need to call from your prices list, not your food list. In your current code, you're basically trying to add the name of each food on your list. Instead of calling

total += food[1]
call
total += prices[a]

which should print the prices of each item, not the name.
:grinning:


#5

Sorry, in the above, I meant to say

total += prices[i]

#6

I was stuck until I read your answer. I was adding "food" too instead "prices". Thank you very much


#8

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