was trying to declare variable t in the first iteration of a recursion
class c:
def __init__(self, a):
self.n=a
def a():
t=c(5)
def b():
print(t.n)
b()
does print t
def d():
try:
t
print(t.n)
except:
t=c(5)
d()
doenst print t
I don't understand the difference and why in the first function does work and the second doesn't
CodePudding user response:
it won't print t
because t
is a local variable to each function call and is not recognized in the context of the other calls to d
. if you want to use it you either have to make it global or pass it as an argument
def d(t=None):
try:
print(t.n)
except:
t=c(5)
d(t=t)
d()
More explanation
As you can see in the picture an Infinite number of function calls is made until a stack overflow error happens which leads to the termination of your running program because it never breaks out of the try-except block because each time a function call is made t
is defined locally to the function call and make another call which doesn't have t
defined in it's scope.