Stocking Out


I cant find any error here :

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

gives me :
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


the problem is here:

stock = stock[item] - 1

this line will overwrite your stock dictionary with a integer, lets say the first product a customer buys is banana, then stock will become 5.

So now, your dictionary is now a integer.

Make to update the stock value of item


Exacly, now I understand what the problem is, but i still don't know a way to fix it.
Can you help me with that?


well, to get access to a value belonging to a dictionary key we can do:


no we want to assign a new value to this dictionary value, just like with normal variable what we want to update should be at the left side of the equal sign:

dictionary_name[key_name] = "new value"


So, what i have to do is :

stock[item] = stock[item] - 1

But with that i still have the same issue


that should work, can i see an updated version of your full code?


It seems like it was some kind of bug in the web page, i updated the page and i got no error message now.
Thanks for your help :slight_smile:


Please, could someone explain what is the answer of this code? What does it give?Or Is it just for script understanding? because I don't catch that is the point of all of it?

My console window gives me 5,5 or 4 5,5 5,5 5,5 depending were i put my print function :slight_smile:



This topic has been solved, so its closed

You should make a new (linked) topic if you still need help when the replies in this topic are sufficient, see guidelines