Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

python - "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)

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!

question from:https://stackoverflow.com/questions/15367760/unboundlocalerror-local-variable-referenced-before-assignment-after-an-if-sta

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...