ProgrammingHardPython · GATE DA · Advanced
What is printed?
What is printed?
def f():
for i in range(3):
try:
if i == 1:
continue
if i == 2:
return 'ret'
finally:
print('f', i, end=' ')
return 'end'
print(f())- A. f 0 f 1 f 2 end
- B. f 0 f 1 ret
- C. f 0 f 2 ret
- D. f 0 f 1 f 2 ret
Correct answer: D. f 0 f 1 f 2 ret
finally runs on every iteration, including the continue at i=1 and the return at i=2; the loop never reaches 'end', so the call returns 'ret' after the third finally print.
More Python Programming questions
- What is printed? python class A: def f(self): return 'A' class B(A): def f(self): return 'B' + super().f() class C(A): def f(self): return…
- What is printed? python def gen(): x = yield 1 print('got', x) y = yield x 2 return y g = gen() print(next(g)) print(g.send(10)) try…
- What is printed? python funcs = [] for i in range(3): funcs.append(lambda x=i: x 10) funcs.append(lambda: i 10) print([f() for f in funcs])
- What is printed? python class Tag: items = [] n = 0 def add(self, v): self.items += [v] self.n += 1 a, b = Tag(), Tag() a.add('x')…
- What is printed? python x = 10 class K: x = 20 ys = [x + i for i in range(2)] print(K.ys)
- What is printed? python import itertools data = [1, 1, 2, 1, 1, 1, 3] print([(k, len(list(g))) for k, g in itertools.groupby(data)])…