ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
def gen():
for i in range(3):
x = yield i
print("got", x, end="; ")
g = gen()
print(next(g), end="; ")
print(g.send("A"), end="; ")
print(next(g))- A. 0; 1; 2
- B. 0; got A; 1; got A; 2
- C. 0; got None; 1; got A; 2
- D. 0; got A; 1; got None; 2
Correct answer: D. 0; got A; 1; got None; 2
next(g) runs to the first yield and returns 0. send("A") resumes it with x = "A", prints 'got A', and stops at the next yield, returning 1. A plain next() resumes with x = None. Generators pause at each yield and keep their local state.
More Python Programming questions
- What is printed? python a = 256; b = 256 c = [1, 2]; d = [1, 2] print(a == b, c == d, c is d, c[:] is c)
- What is printed? python t = (1, [2, 3], 4) try: t[1] += [5] except TypeError as e: print("error", end=" ") print(t)
- What is printed? python def f(): try: return "try" finally: print("finally", end=" ") def g(): try: return "try" finally: return "finally"…
- What is printed? python nums = [3, 1, 2] r = nums.sort() s = sorted(nums, reverse=True) print(r, nums, s)
- What is printed? python x = 10 def outer(): x = 20 def inner(): nonlocal x x += 1 return x return inner() + x print(outer(), x)
- What is printed? python d = {} d[1] = "a" d[1.0] = "b" d[True] = "c" print(d, len(d))