ProgrammingModerateInfosys · Accenture · Capgemini pattern

What is printed?

What is printed?
x = 10

def f():
    x += 1
    return x

try:
    f()
except Exception as e:
    print(type(e).__name__)
  1. A. 10
  2. B. NameError
  3. C. UnboundLocalError
  4. D. 11

Correct answer: C. UnboundLocalError

Because x is assigned inside f, the compiler treats x as local for the WHOLE function. x += 1 then reads the local x before it has a value, which raises UnboundLocalError. A 'global x' line would fix it.

More Python Programming questions

Exams that ask this topic