Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"UnboundLocalError: local variable referenced before assignment" after an if statement

Tags:

python

I have also tried searching for the answer but I don't understand the answers to other people's similar problems...

tfile= open("/home/path/to/file",'r')   def temp_sky(lreq, breq):     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 print temp_sky(60, 60) print temp_sky(10, -10) 

I get the following error

7.37052488 Traceback (most recent call last): File "tsky.py", line 25, in <module>   print temp_sky(10, -10) File "tsky.py", line 22, in temp_sky   return T UnboundLocalError: local variable 'T' referenced before assignment 

The first print statement works correctly but it won't work for the second. I have tried making T a global variable but this makes both answers the same! Please help!

like image 209
user1958508 Avatar asked Mar 12 '13 17:03

user1958508


People also ask

How do you fix UnboundLocalError local variable referenced before assignment?

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .

How do I fix UnboundLocalError local variables?

UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global. Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.

What does it mean if local variable is referenced before assignment?

Ad. The “local variable referenced before assignment” error occurs when you give reference of a local variable without assigning any value.

How do I change a local variable to global in Python?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.


1 Answers

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 
like image 59
shx2 Avatar answered Oct 11 '22 17:10

shx2