ProgrammingVery hardHCL · Tech Mahindra · Python placement

What does the following Python 3 code print? x = 100 def f(): print(x) x = 5 try: f() except UnboundLocalError: print("UnboundLocalError")

  1. A. NameError
  2. B. UnboundLocalError
  3. C. 100
  4. D. 5

Correct answer: B. UnboundLocalError

Because x is assigned anywhere in f, Python treats it as local for the whole function body, so the print(x) before the assignment refers to an as-yet-unbound local, raising UnboundLocalError.

More Python Programming questions

Exams that ask this topic