ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
x = 1
def outer2():
    x = 2
    def inner():
        print(x)
    x = 3
    return inner
outer2()()
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. UnboundLocalError

Correct answer: C. 3

inner closes over outer2's local x, not the module-level x. By the time inner actually runs (after outer2() returns the function and it is called), x inside outer2 has been reassigned to 3.

More Python Programming questions

Exams that ask this topic