ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def risky(n):
    if n == 1: raise KeyError(n)
    if n == 2: raise IndexError(n)
    return n
res = []
for n in range(4):
    try:
        res.append(risky(n))
    except LookupError as e:
        res.append(type(e).__name__[0] + str(e))
print(res)
  1. A. [0, 'K1', 'I2', 3, None]
  2. B. [0, 'K1', 'I2', 3]
  3. C. [0, "K'1'", 'I2', 3]
  4. D. [0, 'L1', 'L2', 3]

Correct answer: B. [0, 'K1', 'I2', 3]

KeyError and IndexError both derive from LookupError. str() of a KeyError gives the repr of its key, but for an int key that is just '1'.

More Python Programming questions

Exams that ask this topic