ProgrammingHardInfosys · Python · Advanced
What is printed?
What is printed?
def g():
x = yield 1
print('got', x)
y = yield x * 2
print('got', y)
it = g()
print(next(it))
print(it.send(5))
try:
it.send(7)
except StopIteration:
print('end')- A. 1 / got 5 / 5 / got 7 / end
- B. 1 / got None / 0 / got None / end
- C. 1 / got 5 / 10 / got 7 / end
- D. 1 / 10 / got 5 / got 7 / end
Correct answer: C. 1 / got 5 / 10 / got 7 / end
next() runs to the first yield (1); send(5) makes x = 5, prints 'got 5' and yields 10; send(7) sets y, prints 'got 7' and the generator ends, raising StopIteration.
More Python Programming questions
- What is printed? python def mk(): n = 0 def inc(): nonlocal n n += 1 return n return inc a, b = mk(), mk() print(a(), a(), b(), a())
- What is printed? python class C: v = [] n = 0 def add(self, x): self.v.append(x) self.n += 1 a, b = C(), C() a.add(1); b.add(2); b.add(3)…
- What is printed? python print(1 < 2 < 3, 3 > 2 > 2, 1 == 1 in [1], not 1 == 2, 2 3 2)
- What is printed? python a = [[0] 2] 2 a[0][0] = 1 b = [[0] 2 for in range(2)] b[0][0] = 1 print(a, b)
- What is printed? python def f(n): try: if n == 0: raise ValueError return 10 // (n - 1) except ZeroDivisionError: return -1 except…
- What is printed? python a, b, c = range(5) x, (y, z) = 1, 'hey' print(a, b, c, x, y, z)