ProgrammingHardInfosys HackWithInfy · TCS CodeVita
What does the following Python 3 code print? try: d = {} print(d["missing"]) except KeyError: print("KeyError")
- A. missing
- B. None
- C. NameError
- D. KeyError
Correct answer: D. KeyError
Indexing a dict with a key that isn't present raises KeyError, not a default value.
More Python Programming questions
- What does the following Python 3 code print? try: s = "abc" print(s[10]) except IndexError: print("IndexError")
- What does the following Python 3 code print? try: x = int("12a") except ValueError: print("ValueError")
- What does the following Python 3 code print? try: def f(a, b): return a + b f(1) except TypeError: print("TypeError")
- What does the following Python 3 code print? try: x = [1, 2] + (3, 4) except TypeError: print("TypeError")
- What does the following Python 3 code print? class MyErr(Exception): pass try: raise MyErr("custom") except MyErr as e: print("caught", e)
- What does the following Python 3 code print? def f(): for i in range(3): if i == 1: continue print(i, end="") print() f()