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:
- Initialize the variable: Ensure that you assign a value to the variable before referencing it within the same scope.
- Check the variable scope: Verify that you are not trying to access the variable from outside its defined scope.
- 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
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:
Accessing global variable without 'global' keyword
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:
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.