ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def acc():
    total = 0
    while True:
        x = yield total
        if x is None:
            return total
        total += x
g = acc()
next(g)
g.send(5)
g.send(7)
try:
    g.send(None)
except StopIteration as e:
    print(e.value)
  1. A. 5
  2. B. 7
  3. C. 12
  4. D. 0

Correct answer: C. 12

Each send resumes the yield with the sent value and yields the new total. Sending None makes the generator return 12, which is stored in StopIteration.value.

More Python Programming questions

Exams that ask this topic