ProgrammingHardPython · GATE DA · Advanced

What is printed?

What is printed?
def gen():
    x = yield 1
    print('got', x)
    y = yield x * 2
    return y
g = gen()
print(next(g))
print(g.send(10))
try:
    g.send(7)
except StopIteration as e:
    print('stop', e.value)
  1. A. 1 / got 10 / 20 / stop None
  2. B. 1 / got 10 / 10 / stop 7
  3. C. 1 / got 10 / 20 / stop 7
  4. D. 1 / got None / 20 / stop 7

Correct answer: C. 1 / got 10 / 20 / stop 7

The first next runs to the first yield (prints 1 only). send(10) makes x = 10, prints 'got 10' and yields 20. send(7) binds y = 7, and the return value 7 travels in StopIteration.value.

More Python Programming questions

Exams that ask this topic