Error in nonlocal keyword in python

Question:

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()
Asked By: bner341

||

Answers:

inner() is enclosed in outer()

No, inner is not enclosed in outer (not defined within the scope of outer), you’re only calling inner from outer; there isn’t any closure here.

Answered By: Moses Koledoye
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.