ProgrammingHardCognizant GenC · Python

What is printed?

What is printed?
def mk():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc
a, b = mk(), mk()
print(a(), a(), b(), a())
  1. A. 1 2 1 3
  2. B. 1 2 3 4
  3. C. 1 1 1 1
  4. D. 1 2 2 3

Correct answer: A. 1 2 1 3

Each mk() call creates its own cell for n; a and b count independently, so a gives 1, 2, then 3 while b gives 1.

More Python Programming questions

Exams that ask this topic