Stocking out


#1



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 i in food:
        if stock[i] > 0:
             total = total + prices[i]
             stock = stock[i] - 1
    return total
    print(shopping_list)
    
this is my code 


ERROR-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

Your code is right by otherwise, but look at this line

stock = stock[i] - 1

You are dealing with i from stock, so why wouldn't your variable be called as stock[ i ] too?


#3

thank for replying but can u explain in a more elaborative manner?


#4

You are subtracting from a variable, so making a new variable doesn't work and you have to subtract from the older one.


#5

So i shall write: stock = stock - 1 ?


#6

Not quite right. Call to both stock- variables with [i]

stock[i] = stock[i] - 1

#7

Thank u so much sir.


#8

No any problemo. :slight_smile:


#9

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