ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def g():
for i in range(3):
try:
yield i
finally:
print(f"f{i}", end=" ")
for v in g():
if v == 1:
break
print("end")- A. f0 end
- B. f0 f1 end
- C. f0 f1 f2 end
- D. f0 end f1
Correct answer: B. f0 f1 end
Leaving the loop with break abandons the generator while it is paused at yield 1; when it is garbage-collected (immediately in CPython), close() raises GeneratorExit there, which runs the finally and prints f1 before 'end'.
More Python Programming questions
- What is printed? python def deco(cls): orig = cls.init def init(self, a): orig(self, a) self.ok = True cls.init = init return cls @deco…
- What is printed? python import functools @functools.singledispatch def show(x): return "obj" @show.register def (x: int): return "int"…
- What is printed? python def f(): x = 0 def inc(): nonlocal x x += 1 return x return [inc() for in range(3)], x print(f())
- What is printed? python def f(kw): return list(kw) print(f(b=1, a=2), f(dict(z=0), y=1), f({"1": 1}))
- What is printed? python class A: def getitem(self, k): return k a = A() print(a[1], a[1:3], a[::2], a[1, 2:3], a[...])
- What is printed? python print([int(t, 0) for t in " 12000 t-0b101 +7 ".split()])