Stocking Out


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

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

What's wrong with my code ?


Remember to include the subscript on the left side, as well.


what d you mean by the subscript on the left ?
i don't get it


Bracket syntax denotes index. Whether that is sequential, as in a list or tuple (or set) or arbitrary as in a dictionary.


stock is a dictionary. When we write, stock = ... we overwrite that dictionary.

stock[item] = ...

sets only that item in the dictionary. item refers to the key, and stock[item] refers to the value.


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