0

this code

def gen(x):
    def f():
        return x

    return f

print(gen(1)())

works well.

but when i run this code,

def gen(x):
    def f():
        x += 1
        return x

    return f

print(gen(1)())

I got an error shows that

UnboundLocalError: local variable 'x' referenced before assignment

what happened to it? and How to understand the closure of python3 .

pexeer
  • 685
  • 5
  • 8

1 Answers1

2
def gen(x):
    def f():
        nonlocal x # add this line
        x += 1
        return x

    return f

print(gen(1)())
HYRY
  • 94,853
  • 25
  • 187
  • 187