LearnFrenzy
Sign in Take a free test

Iterators and Generators · Predict the Output · Question 13

Sending values into a generator Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following Python program?

main.py
def accumulator():
    total = 0
    while True:
        x = yield total
        total += x

acc = accumulator()
print(next(acc), acc.send(5), acc.send(10), acc.send(-3))
  • A None 5 15 12
  • B 0 5 10 -3
  • C 0 5 15 12 Correct
  • D 5 15 12 12
Correct Answer: Option C

next() runs to the first yield (total 0). Each send() becomes the value of that yield, the total grows, and the loop yields the new total.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links