ProgrammingVery hardPython · GATE DA · Advanced

What is printed?

What is printed?
def make():
    n = 0
    def inc():
        n += 1
        return n
    return inc
try:
    print(make()())
except Exception as e:
    print(type(e).__name__)
def make2():
    n = [0]
    def inc():
        n[0] += 1
        return n[0]
    return inc
c = make2(); c(); print(c(), make2()())
  1. A. UnboundLocalError / 2 1
  2. B. UnboundLocalError / 2 2
  3. C. UnboundLocalError / 1 1
  4. D. NameError / 2 1

Correct answer: A. UnboundLocalError / 2 1

n += 1 makes n local to inc, so reading it first raises UnboundLocalError (a NameError subclass, but the exact type name printed is UnboundLocalError). The list version mutates a closed-over object; each make2() has its own list.

More Python Programming questions

Exams that ask this topic