close

[Solved] “UnboundLocalError: local variable referenced before assignment” after an if statement

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error “UnboundLocalError: local variable referenced before assignment” after an if statement 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 “UnboundLocalError: local variable referenced before assignment” after an if statement Error Occurs?

Today I get the following error “UnboundLocalError: local variable referenced before assignment” after an if statement in python.

How To Solve “UnboundLocalError: local variable referenced before assignment” after an if statement Error ?

  1. How To Solve “UnboundLocalError: local variable referenced before assignment” after an if statement Error ?

    To Solve “UnboundLocalError: local variable referenced before assignment” after an if statement Error I was confused why I was getting “local variable referenced before assignment” because I was calling a FUNCTION that I knew was already defined:

  2. “UnboundLocalError: local variable referenced before assignment” after an if statement

    To Solve “UnboundLocalError: local variable referenced before assignment” after an if statement Error I was confused why I was getting “local variable referenced before assignment” because I was calling a FUNCTION that I knew was already defined:

Solution 1

Your if statement is always false and T gets initialized only if a condition is met, so the code doesn’t reach the point where T gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.

Try:

def temp_sky(lreq, breq):
    T = <some_default_value> # None is often a good pick
    for line in tfile:
        data = line.split()
        if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:            
            T = data[2]
    return T

Solution 2

FWIW: I got the same error for a different reason. I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title… who might have made the same mistake I did.

I was confused why I was getting “local variable referenced before assignment” because I was calling a FUNCTION that I knew was already defined:

def job_fn(job):
  return job + ".job"

def do_something():
  a = 1
  b = 2
  job_fn = job_fn("foo")

do_something()

This was giving:

UnboundLocalError: local variable 'job_fn' referenced before assignment

Took me a while to see my obvious problem: I used a local variable named job_fn which masked the ability to see the prior function definition for job_fn.

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