ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def gen():
    for i in range(3):
        x = yield i
        print("got", x, end="; ")
g = gen()
print(next(g), end="; ")
print(g.send("A"), end="; ")
print(next(g))
  1. A. 0; 1; 2
  2. B. 0; got A; 1; got A; 2
  3. C. 0; got None; 1; got A; 2
  4. D. 0; got A; 1; got None; 2

Correct answer: D. 0; got A; 1; got None; 2

next(g) runs to the first yield and returns 0. send("A") resumes it with x = "A", prints 'got A', and stops at the next yield, returning 1. A plain next() resumes with x = None. Generators pause at each yield and keep their local state.

More Python Programming questions

Exams that ask this topic