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?

A

The first version prints 0, and the second prints 1

B

The first version raises UnboundLocalError; the second version runs and prints 1

C

Both versions raise UnboundLocalError, because count is always local to make_counter, never to increment

D

Both versions print 1, since Python already knows count refers to the enclosing scope