Stocking Out Error?


#1

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

this is the code I entered:

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 food:
        if stock[item] > 0:
            total = total + prices[food]
            stock = stock[item] - 1
    return total

What did I do wrong? It gives me this error: Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: local variable 'stock' referenced before assignment


#2

the problem is here:

stock = stock[item] - 1

this will not update stock, at least not correctly. so, stock is our dictionary, banana is a key, and 6 is its value, agree?

so lets say i buy i banana, which gives the following:

stock = stock["banana"]  -1

which gives:

stock = 6 - 1

which gives:

stock = 5

so now, you overwrote your dictionary with an integer

try to only update the value of your dictionary (number of items in stock)

then, here:

total = total + prices[food]

food is a list, it can't be used as key. What should it be instead?


#3

should it be [item]?


#4

yes, it should be item


#5

So does this mean I have to write under the for loop an if statement for each item in the list stock?


#6

no, that doesn't sound right. Can i see an updated version of your code?


#7

So this is what my code currently looks like:
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 food:
if item > 0:
total = total + prices[item]
item = item - 1
return total

and I still keep getting this error: Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: unsupported operand type(s) for -: 'str' and 'int'

I still don't really understand what I'm doing wrong...


#8

here:

item = item - 1

item is a product (for example apple) how does apple - 1 work? You should use the stock dictionary


#9

Ahh okay I got it now!


#10