Local variable referenced before assignment in Python

Local variable referenced before assignment in Python

If you see the "UnboundLocalError: Local variable referenced before assignment" error in Python, here are some steps you can take to fix it, along with examples:

Fixing: Local variable referenced before assignment Error in Python

  1. Check your function to see if you are trying to use a local variable before you have assigned it a value. For example:
def example():
    # This will cause the error because 'num' is not yet defined
    print(num)

    num = 7

example()
  1. If you want to use the global version of the variable, add the "global" keyword to the function definition, like this: "global my_var". For example:
count = 0

def example():
    global count
    print(count)  # Prints 0

    count = 3

example()
  1. If you have a nested function and want to assign a value to a local variable from the outer function, use the "nonlocal" keyword in the inner function definition. For example:
def outer():
    message = ''

    def inner():
        nonlocal message
        message = 'hello world'
        print(message)

    inner()

    print(message)  # Prints 'hello world'

outer()
  1. Alternatively, you can pass the global variable as an argument to the function and use it to assign a new value to the variable. For example:
count = 0

def example(first):
    full_count = first + 2
    return full_count

result = example(count)
print(result)  # Prints 2
  1. Another option is to return a value from the function and use that value to reassign the global variable. For example:
count = 0

def example():
    print(count)  # Prints 0

    new_count = 3
    return new_count

result = example()
print(result)  # Prints 3

count = result
print(count)  # Prints 3

Remember that when you assign a value to a variable in a function, it becomes a local variable unless you explicitly declare it as global. If you assign a value to a variable in a function's body, the local variable will shadow any global variables with the same name.

Conclusion

The Python "UnboundLocalError: Local variable referenced before assignment" error occurs when you try to use a local variable in a function before you have assigned a value to it. To fix this error, you can either declare the variable as global by using the "global" keyword in the function definition, or you can pass the variable as an argument to the function and use it to assign a new value to the variable. Alternatively, you can return a value from the function and use that value to reassign the global variable. If you have a nested function and want to assign a value to a local variable from the outer function, you can use the "nonlocal" keyword.

Related: