ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def g():
    for i in range(3):
        try:
            yield i
        finally:
            print(f"f{i}", end=" ")
for v in g():
    if v == 1:
        break
print("end")
  1. A. f0 end
  2. B. f0 f1 end
  3. C. f0 f1 f2 end
  4. D. f0 end f1

Correct answer: B. f0 f1 end

Leaving the loop with break abandons the generator while it is paused at yield 1; when it is garbage-collected (immediately in CPython), close() raises GeneratorExit there, which runs the finally and prints f1 before 'end'.

More Python Programming questions

Exams that ask this topic