ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def gen7():
    try:
        yield 1
        yield 2
    finally:
        print("cleanup")
g = gen7()
print(next(g))
g.close()
  1. A. 1
  2. B. 1 cleanup
  3. C. cleanup 1
  4. D. 1 2 cleanup

Correct answer: B. 1 cleanup

next(g) runs to the first yield, printing nothing yet and returning 1. g.close() throws GeneratorExit into the generator at that yield point, which triggers the finally block and prints 'cleanup'.

More Python Programming questions

Exams that ask this topic