Question discussion

What is the output of the following Python code?def gen(): yield 1 yield 2 g = gen() print(next(g), next(g), next(g, 'end'), next(g, 'end'))

2386Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

def gen():
    yield 1
    yield 2
g = gen()
print(next(g), next(g), next(g, 'end'), next(g, 'end'))
  • AStopIteration is raised
  • B1 2 end end
  • C1 2 end None
  • D1 2 None None
Correct answer: B

Explanation

After two values the generator is exhausted, and next(g, 'end') returns the supplied default instead of raising StopIteration each time it is called.

Discussion 0

Nobody has replied yet. Start the discussion!