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!
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 .
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.
Ad. The “local variable referenced before assignment” error occurs when you give reference of a local variable without assigning any value.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With