Home > Net >  cannot change integer variable from nested function
cannot change integer variable from nested function

Time:08-03

As we know nested functions can access the outer function variables like the below code.

def a():
    i=[2]
    
    def b():
        i.append(1)
        print(i)
    b()
a() #output: [2,1]

However, for the below code I am getting error

def a():
    i=0
    
    def b():
        i=i 1
        print(i)
    b()
a() ###UnboundLocalError: local variable 'i' referenced before assignment

What am I missing here?

CodePudding user response:

The issue appears on the second i from i=i 1. With the first i you are shadowing the outer scope variable with a local i and then attempt to use it before it was initialized. To solve this you can use the nonlocal keyword:

def a():
    i = 0

    def b():
        nonlocal i
        i = i   1
        print(i)

    b()


a()  # outputs 1
  • Related