close

[Solved] Python 3: UnboundLocalError: local variable referenced before assignment

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python 3: UnboundLocalError: local variable referenced before assignment in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python 3: UnboundLocalError: local variable referenced before assignment Error Occurs?

Today I get the following error Python 3: UnboundLocalError: local variable referenced before assignment in python.

How To Solve Python 3: UnboundLocalError: local variable referenced before assignment Error ?

  1. How To Solve Python 3: UnboundLocalError: local variable referenced before assignment Error ?

    To Solve Python 3: UnboundLocalError: local variable referenced before assignment Error To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

  2. Python 3: UnboundLocalError: local variable referenced before assignment

    To Solve Python 3: UnboundLocalError: local variable referenced before assignment Error To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

Solution 1

If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.

In your case, Var1 is considered as a local variable, and it’s used before being set, thus the error.

To solve this problem, you can explicitly say it’s a global by putting global Var1 in you function.

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1
function()

Solution 2

You can fix this by passing parameters rather than relying on Globals

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read