ProgrammingVery hardProduct company OA
What is printed?
What is printed?
def f():
out = []
for i in range(4):
try:
if i == 1: continue
if i == 2: raise KeyError(i)
if i == 3: return out
out.append(i)
except KeyError as e:
out.append(-e.args[0])
else:
out.append("e")
finally:
out.append("f")
return out + ["end"]
print(f())- A. [0, 'e', 'f', 'f', -2, 'f', 'f']
- B. [0, 'e', 'f', 'f', -2, 'f']
- C. [0, 'e', 'f', 'e', 'f', -2, 'f', 'f']
- D. [0, 'e', 'f', 'f', -2, 'f', 'f', 'end']
Correct answer: A. [0, 'e', 'f', 'f', -2, 'f', 'f']
finally runs on every exit from the try – normal, continue, exception and return – while else runs only when the try block falls off its end. i = 0: 0, 'e', 'f'. i = 1: continue skips else but not finally → 'f'. i = 2: handler appends −2, then 'f'. i = 3: return out fixes the object to return, then finally appends one more 'f' to that same list, so the caller sees it. Seven items; 'end' is never added because the final return is not reached.
More Python Programming questions
- What is printed? python rows = [("x", 2), ("y", 1), ("z", 2), ("w", 1), ("v", 3)] a = sorted(rows, key=lambda r: r[1], reverse=True) b =…
- What is printed? python class P: def init(self, x, y): self.x, self.y = x, y def eq(self, o): return self.x == o.x def hash(self): return…
- What is printed? python it = iter(range(10)) a = list(zip(it, "ab")) b = next(it) c = [x for x in it if next(it, 0) % 3] print(a, b, c)
- What is printed? python def tag(t): print("make", t, end=" ") def deco(fn): print("wrap", t, end=" ") def inner(a): return f"<{t}>" +…
- What is printed? python x = 1 class K: x = 2 a = [x for in range(2)] b = [x i for i in range(x + 1)] def m(self): return x print(K.a, K.b…
- What is printed? python data = [5, 3, 8, 1] out = [] while (n := len(data)) > 1: first, data = data data[-1] += first out.append((n…