Exercise 11/13 - I can't finde problem


#1

i have that 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
}
def compute_bill(food):
total = 0
for key in food:
total = total + food[key]
return total

Write your code below!
print compute_bill(stock)

the system sey me "Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str". What is my problem?


#2

You can not use a dictionary as your input parameter of your function it only takes lists by the way it is programmed.

Should be

print compute_bill(shopping_list)

#3

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

Write your code below!

shop_list = [['banana'],['apple'],['orange'],['pear']]
print compute_bill(shop_list)
but it doesn't work(( system write "list indices must be integers, not list"


#4

@umbra070

I wonder if your program is all correct.

Code that passes

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):
    cost = 0
    for item in food:
        cost += prices[item]
    return cost

compute_bill(shopping_list)

#5

i do that and it work. but i don't understand, why in my code "total += food[key]" make an error, but your code "total += prices[key]" is working?


#6

@umbra070

Read what you have in your function, and compare it to my function you will see quickly why.


#7

i thing i undderstend... food is string, but your function using dictionary. That's why?


#8

@umbra070

Yup, in order to access information in a string you have to use the index, or use the string.index() built-in to find the index of the object you are looking for then use the index to get the information.

Dictionaries on the other hand you have to use the key to find the value, because of this your code was bugged and would not work.


#9

thank's you very much))