ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def f():
    out = []
    for i in range(4):
        try:
            if i == 1: continue
            if i == 2: raise KeyError(i)
            if i == 3: return out
            out.append(i)
        except KeyError as e:
            out.append(-e.args[0])
        else:
            out.append("e")
        finally:
            out.append("f")
    return out + ["end"]
print(f())
  1. A. [0, 'e', 'f', 'f', -2, 'f', 'f']
  2. B. [0, 'e', 'f', 'f', -2, 'f']
  3. C. [0, 'e', 'f', 'e', 'f', -2, 'f', 'f']
  4. D. [0, 'e', 'f', 'f', -2, 'f', 'f', 'end']

Correct answer: A. [0, 'e', 'f', 'f', -2, 'f', 'f']

finally runs on every exit from the try – normal, continue, exception and return – while else runs only when the try block falls off its end. i = 0: 0, 'e', 'f'. i = 1: continue skips else but not finally → 'f'. i = 2: handler appends −2, then 'f'. i = 3: return out fixes the object to return, then finally appends one more 'f' to that same list, so the caller sees it. Seven items; 'end' is never added because the final return is not reached.

More Python Programming questions

Exams that ask this topic