ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
def gen7():
try:
yield 1
yield 2
finally:
print("cleanup")
g = gen7()
print(next(g))
g.close()- A. 1
- B. 1 cleanup
- C. cleanup 1
- D. 1 2 cleanup
Correct answer: B. 1 cleanup
next(g) runs to the first yield, printing nothing yet and returning 1. g.close() throws GeneratorExit into the generator at that yield point, which triggers the finally block and prints 'cleanup'.
More Python Programming questions
- What is printed? python fs = [lambda i=i: i for i in range(3)] print([f() for f in fs])
- What is printed? python def outer(): funcs = [] x = 0 for i in range(3): x = x + i funcs.append(lambda: x) return funcs print([f() for f…
- What is printed? python adders = [] for i in range(3): def adder(x, i=i): return x + i adders.append(adder) print(adders[0](10)…
- What is printed? python x = 1 def outer2(): x = 2 def inner(): print(x) x = 3 return inner outer2()()
- What is printed? python counters = [] for i in range(3): j = i 2 counters.append(lambda: j) print([c() for c in counters])
- What is printed? python def deco2(f): print("decorating", f.name) def wrapper(a, kw): return f(a, kw) return wrapper @deco2 def foo()…