ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
x = 10
def g():
    print(x)
    x = 20
try:
    g()
except UnboundLocalError as e:
    print(type(e).__name__)
  1. A. UnboundLocalError
  2. B. 10
  3. C. 20
  4. D. NameError

Correct answer: A. UnboundLocalError

Assigning x inside g makes it a local name for the whole function. The print runs before that assignment, so the local is unbound, and the error is UnboundLocalError, a subclass of NameError.

More Python Programming questions

Exams that ask this topic