ProgrammingHardAccenture pattern

What is printed?

What is printed?
def f(x, y=10):
    def g():
        return x + y
    y = 20
    return g()
print(f(1))
  1. A. 11
  2. B. 21
  3. C. 31
  4. D. TypeError

Correct answer: B. 21

g closes over the enclosing variable y, looked up when g() is actually CALLED, by which time y has been reassigned to 20. So g() computes x + y = 1 + 20 = 21.

More Python Programming questions

Exams that ask this topic