ProgrammingHardTCS CodeVita · GATE CS · Advanced
What does the following Python 3 code print? try: s = "abc" print(s[10]) except IndexError: print("IndexError")
- A. IndexError
- B. None
- C. ''
- D. KeyError
Correct answer: A. IndexError
A single out-of-range index on a string raises IndexError (unlike slicing, which would just return an empty string).
More Python Programming questions
- 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()
- What does the following Python 3 code print? def f(): for i in range(5): if i == 3: break else: print("else-no-break") print(i) f()