Local variable referenced before assignment

In this post, we will see about error Local variable referenced before assignment in Python.

Problem

Let me explain this error with the help of an example.

When you run above program, you will get below output:

Let’s understand why we are getting this error UnboundLocalError.

When Python interpreter parses any function definition and finds any assignment such

Python interpreter treats a as local variable by default.

Since a is considered as local variable, when python executes

it evaluates right-hand side first and tries to find value of variable a. It finds a first time, hence raised this error: UnboundLocalError: local variable referenced before assignment

Solution

Using global

To resolve this, you need to explicitly declare a variable as global and it will resolve this issue.

Let’s implement this solution in our program.

When you run above program, you will get below output:

value of a: 105

As you can see, after declaring global a in incrementA() function, we solved this issue.

💡 Did you know?

Please note that if you don’t use assignment with variable, you won’t get this error.

When you run above program, you will get below output:

value of a: 100

If you use direct assignment without using variable, then also you won’t get this error.

When you run above program, you will get below output:

value of a: 200

Using non-local

You can use nonlocal to resolve this issue if you are using nested functions. nonlocal works in nested functions and generally used when variable should not belong to inner function.

Output:

value of a inside function: 210
value of a: 215

When we use nonlocal, it refers value from nearest enclosing scope.

Let’s change nonlocal to global and you will be able to understand the difference.

Output:

value of a inside function: 110
value of a: 205

As you can see, value of a inside incrementABy10() was 100 due to global a, then it was incremented by 10 and when we used a inside incrementA(), it was 200 as a is considered local variable here and then incremented it by 5.

That’s all about local variable referenced before assignment in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *