A Day at the Supermarket: Stocking Out


I've noticed no one but me seems to have this error message, even though I **think** i'm typing out the exact same code:
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
this is my current 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

# Write your code below!
def compute_bill(food):
    total = 0
    for lol in food:
        if stock[lol] > 0:
            total = total + prices[lol]
            stock = stock[lol] - 1
    return total
Also, what does the error message actually mean? That i haven't defined what 'stock' is?

Thank you for your help!


Hi, @pyplayer53612 ,

When Python processes your definition of the compute_bill function, it finds this line ...

stock = stock[lol] - 1

The assignment to the name stock, without a key, establishes stock as a local variable within the function. As a consequence, the name stock refers to a local variable anywhere it occurs in the function, rather than to the global dictionary, stock.

Then, when Codecademy calls the function to test it, the function begins to execute. When this line is encountered during execution, the Python interpreter finds that the local variable stock has not yet been given a value, and the error is raised ...

if stock[lol] > 0:

You actually need to have the following assignment, with the key, lol, instead of the current assignment statement ...

stock[lol] = stock[lol] - 1

With that assignment, Python updates the global dictionary, stock at the key, lol.



For your for loop, try doing:
stock[lol] = stock[lol] - 1

Python is going to assume the 'stock' is another variable you're defining.

Hope that helps!


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