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))- A. KeyError: 'k' ('k',) 1
- B. KeyError('k') ('k',) 2
- C. None ('k',) 1
- 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
- What is printed? python print([x if x % 2 else -x for x in range(5)], [x for x in range(5) if x % 2 or x == 0])
- What is printed? python print(int(" -0012 "), int("1000"), float("1e3"), int("101", 2), int(-2.9))
- What is printed? python def g(): try: yield 1 yield 2 finally: print("cleanup", end=" ") it = g() print(next(it), end=" ") it.close()…
- What is printed? python data = [4, 7, 1, 9] best = 0 hi = [best := x for x in data if x > best] print(hi, best, "x" in globals())
- What is printed? python class M: def init(self, v): self.v = v def add(self, o): return M(self.v + (o.v if isinstance(o, M) else o)) ms =…
- What is printed? python print(f"{3.14159:.2f}|{42:>5}|{'ab':^6}|{255:#x}|{1234567:,}")