Cluelessly failing on "Making a Purchase"


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096


I have no idea of what should happen...
It just keeps throwing the following Error:

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


i think that the problem might be with the site, but I still have no clue.


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 food in shopping_list:
         total += food # I feel that the error is in this line.
     return total


#2

The error is actually in both of these lines. When you use the food argument in your compute_bill function, food becomes the list through which you will iterate. So you should be going through each item in food.

Next you want to get the price of each item and add those together. The current code will attempt to add the names of the items together, which is why you get the += error. For example: list[key]


#3

That doesn't really make much sense to me...


#4

shopping_list = ['banana', 'orange', 'apple']

stock = {'banana': 6, 'apple': 0, 'orange': 32, 'pear': 15}
    
prices = {'banana': 4, 'apple': 2, 'orange': 1.5, 'pear': 3}

Do you understand till this code?

Now follow the step...

tell me which line of instruction is not clear..

Okay you did first two instructions right way..

def compute_bill(food):
     total = 0

Does anywhere written to loop over shopping_list ?
for food in shopping_list:


#5

i Understand what I'm supposed to do, it's just that I don't understand what I was doing wrong...


#6

This explains the for loop:

For each item in the food list, add the price of that item to total.

for item in food:

Inside the for loop you want to add the price of each item to the total:

total += prices[item]

Then, outside of the for loop, you want to return the total:

return total

#7

for food in shopping_list:
         total += food

These two lines have error.

You have to loop over food list and you're looping over shoping_list?
You have to revise the concept of looping over dictionary.

I will give an example..

my_dictionary = {'a' : 1 , "b": 2, "c": 3, "d": 4}

#If I have to find sum of values I'd do something like this...
total = 0
for  k in my_dictionary:
    total += my_dictionary[k]

print total  # 10

#8

Thank you. That really helped! :slight_smile:
Have a small tree. :evergreen_tree:


#9

I do love trees...

Have a great day, enjoy the coding.


#10

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