Mutating an Outer Local Needs nonlocal
def make_counter():
count = 0
def increment():
count += 1
return count
return increment
counter = make_counter()
print(counter())
Now compare with this version, where the only change is one added line:
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter())
What happens when each version runs?
Sign in to answer questions and track your progress
Sign In