ProgrammingHardPython · GATE DA · Advanced

What is printed?

What is printed?
def f():
    for i in range(3):
        try:
            if i == 1:
                continue
            if i == 2:
                return 'ret'
        finally:
            print('f', i, end=' ')
    return 'end'
print(f())
  1. A. f 0 f 1 f 2 end
  2. B. f 0 f 1 ret
  3. C. f 0 f 2 ret
  4. D. f 0 f 1 f 2 ret

Correct answer: D. f 0 f 1 f 2 ret

finally runs on every iteration, including the continue at i=1 and the return at i=2; the loop never reaches 'end', so the call returns 'ret' after the third finally print.

More Python Programming questions

Exams that ask this topic