Local variable referenced before assignment in Python

Aug 20, 2023#python#scopes

The “local variable referenced before assignment” error occurs in Python when you try to use a local variable before it has been assigned a value.

This error typically arises in situations where you declare a variable within a function but then try to access or modify it before actually assigning a value to it.

Here’s an example to illustrate this error:

def my_function():
    print(x)  # Trying to access x before assigning a value
    x = 10    # Assigning a value to x

my_function()

In this example, you would encounter the “local variable ‘x’ referenced before assignment” error because you’re trying to print the value of x before it has been assigned a value. To fix this, you should assign a value to x before attempting to access it:

def my_function():
    x = 10    # Assigning a value to x
    print(x)  # Now it's safe to access x

my_function()

In the corrected version, the local variable x is assigned a value before it’s used, preventing the error.

Keep in mind that Python treats variables inside functions as local unless explicitly stated otherwise using the global keyword (for global variables) or the nonlocal keyword (for variables in nested functions).

If you encounter this error and you’re sure that the variable should have been assigned a value before its use, double-check your code for any logical errors or typos that might be causing the variable to not be assigned properly.

Using the global keyword

If you have a global variable named letter and you try to modify it inside a function without declaring it as global, you will get error.

letter = "F"

def calculate_grade(grade):
    if grade > 80:
        letter = "A"
    elif grade > 70:
        letter = "B"
    elif grade > 60:
        letter = "C"
    elif grade > 50:
        letter = "D"
    return letter

print(calculate_grade(36))

# ❌ UnboundLocalError: cannot access local variable 'letter' where it is not associated with a value

This is because Python assumes that any variable that is assigned a value inside a function is a local variable, unless you explicitly tell it otherwise.

To fix this error, you can use the global keyword to indicate that you want to use the global variable:

letter = "F"

def calculate_grade(grade):
    global letter  # ✅ Tell Python to use the global variable
    if grade > 80:
        letter = "A"
    elif grade > 70:
        letter = "B"
    elif grade > 60:
        letter = "C"
    elif grade > 50:
        letter = "D"
    return letter

print(calculate_grade(36))

Using nonlocal keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope.

For example, if you have a function outer that defines a variable x, and another function inner inside outer that tries to change the value of x, you need to use the nonlocal keyword to tell Python that you are referring to the x defined in outer, not a new local variable in inner.

Here is an example of how to use the nonlocal keyword:

def outer():
    x = 10  # define a non-local variable in the outer function

    def inner():
        nonlocal x  # tell Python that x is not local
        x = 20  # modify the value of x in the outer scope
        print("inner:", x)  # print 20
    inner()
    print("outer:", x)  # print 20


outer()

If you don’t use the nonlocal keyword, Python will create a new local variable x in inner, and the value of x in outer will not be changed:

def outer():
    x = 10  # define a non-local variable in the outer function

    def inner():
        x = 20  # create a new local variable in the inner function
        print("inner:", x)  # print 20
    inner()
    print("outer:", x)  # print 10


outer()