Reputation: 43
I am just learning python and using codecademy to learn basics but im stuck in an exercise, hoping you guys could hep with.
The course first wants me to define a function called compute_bill
and give it one arguement which is food
.
Then give total
an initial value of 0
and then for each item
in food
list add their value to total
and finally return total
.
this is the prewritten list of prices and stock numbers.
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
and this is the little function that i wrote but course is not accepting it saying compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +=: 'int' and 'str'
def compute_bill(food):
total = 0
for item in food:
total += item
return total
it might be a very stupid question for most of you but i just cant understand what's the problem with it.
Upvotes: 2
Views: 147
Reputation: 167
def compute_bill(food) :
total = 0
for item in food :
if stock[item] != 0 :
total = total + prices[item]
#you also need to update the stock table i won't do it here
return total
food = {"banana","apple","orange"}
print compute_bill(food)
Upvotes: 0
Reputation: 43
I wish i could give you all an upvote. Thanks a lot for answers and advices i've just seen how silly i am.
def compute_bill(food):
total = 0
for key in food:
total += prices[key]
return total
this just did the trick
Upvotes: 1
Reputation: 12563
You are making a couple of mistakes:
1) "food" is a list. Every element there is a string. You can't add a string to a number in Python (and it wouldn't make sense).
2) What you really want to do is to use elements from "food" as keys, and then get prices from "prices" which is a dictionary.
One hint: to get a value for an element 'apple' from prices, you have to do something like:
apple_price = prices['apple']
This will give you the entry from 'prices' stored under the key 'apple', which is an integer equal 2. You can use this price to calculate the total.
Another hint: iterate over the elements in "food" and use these elements to retrieve corresponding prices from "prices" dictionary.
Good luck :)
Upvotes: 2
Reputation: 6012
You almost have it. The for loop is iterating through each string in the food[] array, with that string you need to lookup the price in the prices dictionary.
def compute_bill(food):
total = 0
for key in food:
total += prices[key]
return total
Upvotes: 1
Reputation: 83418
Try:
total += prices[item]
The code in the question is not referring to prices at all.
Upvotes: 0