ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def g():
try:
yield 1
yield 2
except KeyError:
yield "caught"
yield 3
it = g()
print(next(it), it.throw(KeyError), next(it))- A. 1 2 3
- B. 1 caught 2
- C. 1 KeyError 3
- D. 1 caught 3
Correct answer: D. 1 caught 3
throw raises KeyError at the paused `yield 1`; the generator catches it and its next yield ('caught') becomes throw()'s return value. The next next() continues to yield 3.
More Python Programming questions
- What is printed? python def g(): yield 1 raise StopIteration try: print(list(g())) except RuntimeError as e: print("RuntimeError")
- What is printed? python def g(): try: yield 1 finally: print("F", end=" ") it = g() next(it) it.close() print(next(it, "done"))
- What is printed? python import itertools a, b = itertools.tee(iter([1, 2, 3])) next(a); next(a) print(list(b), list(a))
- What is printed? python def nums(): for n in range(5): print(n, end="") yield n r = any(n > 1 for n in nums()) print("", r)
- What is printed? python gen = (i for i in range(3)) print(1 in gen, 1 in gen, list(gen))
- What is printed? python x = 10 class K: x = 20 y = [x + i for i in range(2)] z = (lambda: x)() print(K.y, K.z)