Making a Purchase "Operand type error"


#1

Hello,

i get this error: Oops, try again. compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +: 'int' and 'str'

I understand "unsupported operand type" but not how to fix it.

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 item in food:
total = total + item
return total


#2

total is an integer, item is a string (for example "apple") we want to add the price of apple to total, maybe we can use the prices dictionary somehow?

give it a second to think about it


#3

I tried this code but I still have an error: compute_bill(['apple']) resulted in a TypeError: string indices must be integers, not dict

Write your code below!

def compute_bill(food):
total = 0
for key in food:
total += key[prices]
return total


#4

general syntax:

dictionaryName[keyName]

currently, you try to access a string like its a dictionary and the key being a dictionary


#5

yeah I make a mistake :confused:

That's better but return 4 instead 10.5, it seems returned the first price of stock

Write your code below!

def compute_bill(food):
total = 0
for key in food:
total += prices[key]
return total


#6

a function ends the moment a return keyword is reached

so, your function ends in the first run/iteration of the loop. Place return outside the loop so the whole loop can run, calculating the correct total and not just of the first item


#7

I found my error, I did it many times and qtill not in my head :confused:

Thanks very much for your help :slight_smile:


#8