ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def counter_gen():
    c = 0
    while True:
        cmd = yield c
        if cmd == "reset":
            c = 0
        else:
            c += 1
g = counter_gen()
print(next(g), next(g), next(g), g.send("reset"), next(g))
  1. A. 0 1 2 0 1
  2. B. 0 1 2 3 0
  3. C. 0 1 2 0 0
  4. D. 1 2 3 0 1

Correct answer: A. 0 1 2 0 1

The first next starts the generator and yields 0. Each later next sends None, so c increments. send('reset') sets c to 0 and loops to yield 0; the following next increments to 1.

More Python Programming questions

Exams that ask this topic