Skip to content
Home » UnboundLocalError: local variable referenced before assignment Python

UnboundLocalError: local variable referenced before assignment Python

To solve Python 3: UnboundLocalError: local variable referenced before assignment error follow below methods.

ERROR LOG

UnboundLocalError: local variable referenced before assignment

How to solve Python 3: UnboundLocalError: local variable referenced before assignment ?

When you try to assign a value to a local variable before it has been declared, the UnboundLocalError: local variable referenced before assignment error is raised. You can avoid this problem by making sure that a local variable is declared before assigning it a value.

Outside of necessity, utilizing global variables is widely frowned upon by Python developers since it leads to convoluted and difficult code. However, if you want to use them to do what your code is hinting, simply add the following code to the start of your function:

global Var1, Var2

This tells Python that you do not want to define a Var1 or Var2 variable within the function’s local scope. At module load time, the Python interpreter notices this and decides (right) to search for any references to the aforementioned variables in the global scope.

Also read :

TypeError: unhashable type: ‘dict’
ImportError: No module named PIL