# Stocking out - problems with removing the stock

#1

I’m not sure why it’s not working - it returns 9 instead of 7, I assume there must be a problem with the way that I’m removing the stock count?

def compute_bill(food):
total = 0
for item in food:
if item > 0:
total += prices[item]
stock[key] -= 1

#2

stock[key] -= 1

what is key here?

#3

It refers to the key in the dictionary - sorry I didn’t paste the whole 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
}

def compute_bill(food):
total = 0
for item in food:
if item > 0:
total += prices[item]
stock[key] -= 1
print stock

I’m putting in print stock just to see that it is working

#4

how does python know it? if you call the function with shopping_list as an argument then you’ll get an error.

NameError: global name 'key' is not defined

Instead of key use item .if you don’t understand then print item like you did for stock.

#5

Yes thank you! I managed to understand it must be stock[item] and now I am sitting with this:

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

Now I am getting “calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in {‘orange’: 32, ‘pear’: 14, ‘banana’: 5, ‘apple’: -1} instead of the correct 7” so it seems like it’s maybe a problem with my ‘return stock’?

#6

what should you return? what’s the main point to make that function?

The name of the function is pretty straightforward.

#7

So should it be ‘return total’? Sorry I know I’m being dumb but I’m just struggling with this one so much for some reason… Thanks for your patience.

#8

Managed to get it right… I think in the end I was just having indentation problems Thanks so much for your help, appreciated.

#9

now is it fine?

#10

All good thanks - I just changed the ‘if item > 0’ to ‘if stock[item] > 0’ and fixed the indentation on the return function… I think it was getting confused between stock[item] and price[item] maybe?

#11

keys are same name for both stock and prices dictionaries. so we can work with same loop.
may be confused for first time but now you know

#12

I’m having an indentation problem… points at the 1 and says unindent does not match

#13

I’d recommend going here: https://discuss.codecademy.com/c/python/python-beginner-en-IZ9Ra and creating a new topic, will be more visible and help you get answers quickly. Please remember to also paste your code as it makes it much easier seeing what isn’t matching.

#14

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