ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def f():
    x = 1
    def g():
        return x
    x = 2
    return g
def h():
    for x in [1, 2]:
        pass
    return lambda: x
print(f()(), h()())
  1. A. 1 2
  2. B. 1 1
  3. C. 2 2
  4. D. 2 1

Correct answer: C. 2 2

Closures capture variables, not values: g reads x as it is when called (2). The lambda in h reads x after the loop finished, also 2.

More Python Programming questions

Exams that ask this topic