I am trying to use nonlocal
keyword in python in the following code. inner()
is enclosed in outer()
and I want to create a counter variable that will remember how many times inner()
is called from outer()
. ctr
is defined in outer()
and as nonlocal
in inner()
.
But I am getting error as no binding for nonlocal 'ctr' found
.
def inner1():
nonlocal ctr
ctr=ctr+1
print(' ctr= {0}'.format(ctr))
def outer1():
ctr=0
for i in range(5):
inner1()
outer1()