ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def f():
    try:
        print(y, end=" ")
    except NameError as e:
        print(type(e).__name__, end=" ")
    y = 1
y = 5
f()
print(y)
  1. A. UnboundLocalError 5
  2. B. 5 5
  3. C. NameError 5
  4. D. UnboundLocalError 1

Correct answer: A. UnboundLocalError 5

Because y is assigned inside f, it is local for the whole function body; reading it before assignment raises UnboundLocalError, a subclass of NameError, so the handler catches it and prints the subclass name.

More Python Programming questions

Exams that ask this topic