ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
try:
    r = [1 / x for x in [1, 0, 2]]
except ZeroDivisionError:
    r = "partial?"
g = (1 / x for x in [1, 0, 2])
out = []
try:
    for v in g:
        out.append(v)
except ZeroDivisionError:
    pass
print(r, out, next(g, "end"))
  1. A. partial? [1.0] end
  2. B. [1.0] [1.0] end
  3. C. partial? [1.0] 0.5
  4. D. partial? [] end

Correct answer: A. partial? [1.0] end

An exception inside a list comprehension aborts it before any assignment, so r takes the handler value. With a generator, values produced before the error are already consumed; an exception raised inside a generator finishes it, so next returns the default.

More Python Programming questions

Exams that ask this topic