UnboundLocalError: local variable referenced before assignment

The "UnboundLocalError: local variable referenced before assignment" in Python occurs when you try to access a local variable before it has been assigned a value within the current scope or function. Python requires that you initialize a variable before using it in the same scope to avoid ambiguity and undefined behavior.

To resolve this error, you can follow these steps:

  1. Initialize the variable: Ensure that you assign a value to the variable before referencing it within the same scope.
  2. Check the variable scope: Verify that you are not trying to access the variable from outside its defined scope.
  3. Use global keyword : If you want to access a global variable from within a function, use the global keyword to indicate that the variable is defined in the global scope.

Variable not assigned before use

def example_function(): # UnboundLocalError: 'x' referenced before assignment print(x) x = 10

In this example, the variable "x" is referenced before it is assigned any value within the function. Python raises the UnboundLocalError since the variable is accessed before being defined.

To fix this, assign a value to the variable before referencing it:

def example_function(): x = 10 print(x)

Accessing global variable without 'global' keyword

x = 5 def example_function(): # UnboundLocalError: 'x' referenced before assignment x += 1 example_function()

In this example, the function tries to modify the global variable "x" without using the global keyword. This results in the UnboundLocalError.

To resolve this, use the global keyword to indicate that the variable is in the global scope:

x = 5 def example_function(): global x x += 1 example_function() print(x) # Output: 6

In Python, lexical scoping is the default behavior, where inner scopes can access values from enclosing scopes, but they cannot modify those values unless explicitly declared global using the "global" keyword. When variables are assigned values within a function, they are stored in the local symbol table. However, when referencing variables, Python first looks in the local symbol table, then in the global symbol table, and finally in the built-in names table. This design leads to a restriction where global variables cannot be directly assigned new values within a function, unless they are explicitly named in a global statement. Nevertheless, global variables can be referenced within functions. By adhering to these lexical scoping principles and utilizing the "global" keyword when necessary, Python developers can ensure proper variable behavior and maintain the integrity of variable assignments across different scopes, promoting code reliability and clarity.

Conclusion

By following these best practices and ensuring variable assignment before referencing within the same scope, you can overcome the UnboundLocalError and ensure the proper functioning of your Python code.