ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def f():
    l = []
    for i in range(3):
        try:
            if i == 0:
                raise ValueError
            l.append(i)
        except ValueError:
            l.append("v")
            continue
        finally:
            l.append("f")
        l.append("e")
    return l
print(f())
  1. A. ['v', 'f', 1, 'f', 'e', 2, 'f', 'e']
  2. B. ['v', 1, 'f', 'e', 2, 'f', 'e']
  3. C. ['v', 'f', 'e', 1, 'f', 'e', 2, 'f', 'e']
  4. D. ['v', 'f', 1, 'e', 'f', 2, 'e', 'f']

Correct answer: A. ['v', 'f', 1, 'f', 'e', 2, 'f', 'e']

finally runs even when continue leaves the try statement, so i = 0 gives 'v', 'f' and skips 'e'. For i = 1 and 2 the try succeeds, finally runs, and then the statement after the try appends 'e'.

More Python Programming questions

Exams that ask this topic