ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def outer():
    v = "a"
    def inner():
        return v
    v = "b"
    r1 = inner()
    del v
    try:
        return r1, inner()
    except NameError as e:
        return r1, type(e).__name__
print(outer())
  1. A. ('a', 'NameError')
  2. B. ('b', 'b')
  3. C. ('b', 'UnboundLocalError')
  4. D. ('b', 'NameError')

Correct answer: D. ('b', 'NameError')

A closure sees the current value of the cell, so the first call returns 'b'. After del v the cell is empty and reading it raises NameError ('free variable referenced before assignment'), which is NameError itself, not UnboundLocalError.

More Python Programming questions

Exams that ask this topic