ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def acc():
    total = 0
    while True:
        try:
            x = yield total
        except ValueError:
            total = 0
            continue
        if x is None:
            break
        total += x
    yield "done"

g = acc()
print([next(g), g.send(5), g.send(7), g.throw(ValueError), g.send(2), g.send(None)])
  1. A. [0, 5, 12, 12, 14, 'done']
  2. B. [0, 5, 12, 0, 2, 'done']
  3. C. [0, 5, 12, 0, 2, None]
  4. D. [None, 5, 12, 0, 2, 'done']

Correct answer: B. [0, 5, 12, 0, 2, 'done']

next(g) runs to the first yield and gives 0. send(5) resumes with x = 5, total 5, yields 5; send(7) yields 12. throw(ValueError) raises inside the paused yield, the except resets total to 0 and continue reaches the yield again, so throw itself returns 0. send(2) yields 2. send(None) breaks the loop and the generator yields "done" — throw and send both return the NEXT yielded value.

More Python Programming questions

Exams that ask this topic