Local Variable Referenced Before Assignment in Python

This tutorial will explain why the error local variable referenced before assignment occurs and how it can be resolved.

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable. As the global variables have global scope and can be accessed from anywhere within the program, the user usually tries to use the global variable within a function.

In Python, we do not have to declare or initialized the variable before using it; a variable is always considered local by default. Therefore when the program tries to access the global variable within a function without specifying it as global, the code will return the local variable referenced before assignment error, since the variable being referenced is considered a local variable.

the Solution of local variable referenced before assignment Error in Python

We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.

The below example code demonstrates the code scenario where the program will end up with the “local variable referenced before assignment” error.

count = 10

def myfunc():
    count = count + 1
    print(count)
  
myfunc()

Output:

UnboundLocalError: local variable 'count' referenced before assignment

We need to declare the count variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

count = 10

def myfunc():
    global count
    count = count + 1
    print(count)
  
myfunc()

Output:

11
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.