11/13. Making a Purchase


#1

the exercise it self "https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096"

The code obviously doesn't work, but I really don't know what i'm forgetting, could someone help me figure it out ? Thanks in advance people here are of great help.

btw I receive this error message "Oops, try again. compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +=: 'int' and 'str'"
From that I understand that the code is trying to add a string to the "total" but I don't know how to make it add the price instead.

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

#2

This line is attempting to add a string to a number. Try adding a prices item.

total += prices[produce]

#3

Thanks for the help, but how does the argument food relate to the prices in stock ?


#4

food is a shopping list which string values match the item keys in the prices dictionary.

for item in food:
    total += prices[item]

#5

don't 100% get it but I'll redo the course if I still don't get it at the end... Thanks for the help :wink:


#6

Let's say the shopping list is, ['banana', 'pear', 'orange']

Inside the loop, item will be one of the three, each in turn. So the corresponding prices items will be,

prices['banana']  =>  4
prices['pear']    =>  3
prices['orange']  =>  1.5

See how the items match the keys of the prices dictionary?

total = 0
total += 4
total += 3
total += 1.5

which adds to 8.5.


#7

Ok, so i get what the loop does, "for produce in food:". But it is in the function "def compute_bill(food)" but how is the function related to anything else in the code ? it doesn't refer to the shopping list "shoppinglist = ["pear", "orange", "apple"]" I don't see how at least, it's probably becoming headbangingly stupid for you but I really want to understand what i'm doing


#8

We pass the shopping list into the function parameter as the argument...

print compute_bill(shopping_list)

Inside the function, food is the parameter that takes the list it is passed.

Be sure not to call your function until directed to do so.


#9

Ok... Thanks a lot for the help. Really appreciate it. I really didn't expect such nice people here when I began.


#10

2 posts were split to a new topic: Compute_bill[apple] returns 10.5 instead of 2


#11