Hi @Bharatmani, welcome to the portal. The error that you are receiving is due to the fact that variable temp has been declared inside the if block and hence has its scope only in that block. As you are trying to return it outside the if block, the variable reference is not found and hence the error. Hope this helps!!
In this given problem, the scope is not the root cause.
The problem is incorrect use of
if instead of
def fib(n): a = 1 b = 1 for i in range(n): temp = a + b a = b b = temp print("Id of a", id(a)) print("Id of b",id(b)) print("Id of temp",id(temp)) return temp print(fib(3))
Id of a 10914496 Id of b 10914528 Id of temp 10914528 Id of a 10914528 Id of b 10914560 Id of temp 10914560 Id of a 10914560 Id of b 10914624 Id of temp 10914624 5
C language,) Python intelligently uses reference of
temp thus making it available outside the
But in the code given by @Bharatmani, the
if block was never entered. Thus
temp was never referenced and hence
temp was not available outside the if block.
This would have worked if
if block was entered, though it would not have yielded the desired result.
Have a look at this demonstration below.
def demo(n): if i in range(n): temp = i print ("entered if") print("value of i", i) else: print("did not enter if") print("value of i", i) return temp
print("return value from function", demo(10))
entered if value of i 9 return value from function 9
In this interesting case,
i was randomly assigned a value of
9. If the
if condition was satisfied it would enter the
temp would get an assignment and everything would be fine. This is what happened when
demo(10) was called.
print("return value from function", demo(5))
did not enter if value of i 9 --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) [<ipython-input-64-12ef7b0ebfa5>](https://localhost:8080/#) in <module>() ----> 1 print("return value from function", demo(5)) [<ipython-input-62-3cf8d90e9115>](https://localhost:8080/#) in demo(n) 7 print("did not enter if") 8 print("value of i", i) ----> 9 return temp UnboundLocalError: local variable 'temp' referenced before assignment
i still has this random value of
9. Hence it did not enter the
if block and hence temp was not assigned and was unreferenced, leading to UnboundLocalError.