Stocking Out


#1

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


#2

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


#3

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?


#4

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

dictionary_name[key_name]

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"

#5

So, what i have to do is :

stock[item] = stock[item] - 1

But with that i still have the same issue


#6

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


#7

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:


#8

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:


#9

#10

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