ProgrammingModerateAccenture · Capgemini pattern

What is printed?

What is printed?
d = {"a": 1}
try:
    d["k"]
except KeyError as e:
    print(repr(e), e.args, len(d))
  1. A. KeyError: 'k' ('k',) 1
  2. B. KeyError('k') ('k',) 2
  3. C. None ('k',) 1
  4. D. KeyError('k') ('k',) 1

Correct answer: D. KeyError('k') ('k',) 1

Reading a missing key with [] raises KeyError carrying the key; repr of the exception is KeyError('k') and its args tuple is ('k',). A failed lookup never inserts anything (that is defaultdict behaviour), so len(d) stays 1. "KeyError: 'k'" is how the traceback prints it, not repr.

More Python Programming questions

Exams that ask this topic