“UnboundLocalError:赋值前引用了局部变量";在 if 语句之后 [英] "UnboundLocalError: local variable referenced before assignment" after an if statement
问题描述
我也尝试过寻找答案,但我不明白其他人类似问题的答案...
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)
我收到以下错误
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
第一个打印语句正常工作,但不适用于第二个.我曾尝试将 T 设为全局变量,但这会使两个答案相同!请帮忙!
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!
推荐答案
您的 if
语句始终为 false,并且 T
仅在满足条件时才会初始化,因此代码没有达到 T
获取值的地步(并且由此被定义/绑定).您应该在始终执行的地方引入变量.
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.
试试:
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
这篇关于“UnboundLocalError:赋值前引用了局部变量";在 if 语句之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!