ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
def gen():
try:
x = yield 1
except GeneratorExit:
print("closing")
raise
g = gen()
next(g)
g.close()- A. Nothing is printed
- B. closing
- C. 1 closing
- D. closing 1
Correct answer: B. closing
next(g) advances to the yield, suspending there. g.close() throws GeneratorExit into the generator at that exact point, which is caught, prints 'closing', and then re-raised (as required) to properly finish closing the generator.
More Python Programming questions
- What is printed? python a = 5 def outer(): x = 10 def inner(): nonlocal x x += a return x return inner() print(outer())
- What is printed? python class Temperature: def init(self, celsius=0): self.celsius = celsius @property def fahrenheit(self): return…
- What is printed? python def f(a, b, , c=10, kwargs): return a + b + c + sum(kwargs.values()) print(f(1, 2, d=3, e=4)) print(f(1, 2, c=100))
- What is printed? python class Animal: sound = "..." def makesound(self): return f"{type(self).name} says {self.sound}" class Dog(Animal)…
- What is printed? python def outer(): x = [] def appendVal(v): x.append(v) return x return appendVal f1 = outer() f2 = outer() print(f1(1)…
- What is printed? python def validate(f): def wrapper(x): if x < 0: raise ValueError("negative") return f(x) return wrapper @validate def…