Home > Back-end >  Inner function not printing nonlocal variable
Inner function not printing nonlocal variable

Time:02-23

I have one outer function and 2 inner functions.

def outer():
    x = 'hello'    
    def inner1():
        def inner2():
            nonlocal x
            x = 'python'        
        inner2()
        print(x)
outer()

Please help me understand why the above code is not printing the value of x.

As per my understanding, it should print "hello"

CodePudding user response:

Your code calls outer(), which in turn executes only one statement:

x = 'hello'

As it stands, the code in your question will print nothing.

If you were to add the line print(x) after the call to outer(), it would indeed print "hello", as you have suggested.

If you were to instead add the line inner1() to call the function by that name which is defined inside outer(), then inner1() would in turn call inner2() which would in turn cause x = 'python' to execute, and this would change the value of x and (thanks to the nonlocal x line within inner2()) the statement print(x) within inner1() would cause the code to print "python".

  • Related