ProgrammingModerateInfosys · Accenture · Capgemini pattern

What is printed?

What is printed?
def outer():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

c = outer()
c(); c()
print(c())
  1. A. 3
  2. B. UnboundLocalError
  3. C. 2
  4. D. 1

Correct answer: A. 3

nonlocal lets inc change the n that belongs to outer's call. The closure c keeps that n alive between calls, so the three calls return 1, 2 and 3, and the last one is printed.

More Python Programming questions

Exams that ask this topic