ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
a = 5
def outer():
    x = 10
    def inner():
        nonlocal x
        x += a
        return x
    return inner()
print(outer())
  1. A. 10
  2. B. 5
  3. C. 15
  4. D. UnboundLocalError

Correct answer: C. 15

nonlocal x binds to outer's local x (10). a is just read from the global scope (no nonlocal/global needed for reading). x += a makes x = 10 + 5 = 15, which inner returns and outer passes along.

More Python Programming questions

Exams that ask this topic