Code Problems


#1



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

Oops, try again. compute_bill(['apple']) resulted in a NameError: global name 'key' is not defined


Replace this line with your 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
}

# Write your code below!
def compute_bill(food):
    total = 0
    for item in shopping_list:
        total += prices[key]
    return total


#2

where did key from? In your for loop declaration, you called it the variable holding the product item, not key


#3

Hey @codecoder18935 ,

It seems like @stetim94 is correct: Your compute_bill(food) function references item in the for loop initialization but then references key within the loop. Just go ahead and change one of them to match the other, and your code should be correct. This code references a variable key that was never created.


#4

now I got this:
Oops, try again. compute_bill(['apple']) resulted in a TypeError: unhashable type: 'list'
My code is:
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 item in shopping_list:
total += prices[food]
return total


#5

You'll need to take the shopping list items and compute their prices. Your current code tries to calculate the items themselves.


#6

this line of code:

total += prices[food]

food is a list, where you should use item. (since that contains the items in the run of the loop), also, your for in loop, it is dangerous to use shopping_list, i would use the function parameter (food) since the exercise will call your function with different shopping_lists


#7

What code do you think i should use for the last part? I'm not sure how to change it. I'm new to Python


#8

My code is as follows:

def compute_bill(food):
    total = 0
    for n in food:
        total = total + prices[n]
        stock[n] = stock[n] - 1 
    return total

What this code does is it checks the price of the food in the shopping list and adds those. Hope this helps.