Lesson 11. making a purchase


#1



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

Oops, try again. compute_bill(['apple']) resulted in a TypeError: 'dict' object is not callable

Anyone see a problem?


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 food in shopping_list:
        total += prices(food)
    return total


#2

Needs to be written in subscript form,

    prices[food]

food is the parameter (a list), and shopping_list is not locally defined. To keep it local,

    for item in food:
        ... prices[item]

#3

Thank you for the help.


#4

thanks for your help


#5

I understand the subscript form part... however I'm confused as to how python knows what food is. I didn't define it before using it in the function. How does it know that food refers to each key in shopping list, and then each key in prices?


#6

Python knows what food is because it is defined as a list before being passed in to the function. Outside of the function, we defined shopping_list which we then used as the argument in a call to the compute_bill function.

compute_bill(shopping_list)

The parameter, food in,

def compute_bill(food):

is a local variable that references that list.

A list is an iterable, hence we can iterate over it, examining one element at a time. The value of these elements are strings that match (or at last should match) the key names in the two dictionaries, stock and prices.

stock['apple']  =>  0
prices['apple'] =>  2

#10