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')
  1. A. 1 / got 5 / 5 / got 7 / end
  2. B. 1 / got None / 0 / got None / end
  3. C. 1 / got 5 / 10 / got 7 / end
  4. 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

Exams that ask this topic