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")
- A. NameError
- B. UnboundLocalError
- C. 100
- 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
- What does the following Python 3 code print? print("%d-%s-%.2f" % (5, "hi", 3.14159))
- What does the following Python 3 code print? print(list(filter(lambda x: x % 2 == 0, range(10))))
- What is printed? python print(type(10 / 5))
- Which of these built-in Python types is immutable?
- What is printed? python s = "placement" print(s[2:5])
- What is printed? python print(len({1, 2, 2, 3, 3, 3}))