ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
class K:
    n = 3
    a = [i for i in range(n)]
    try:
        b = [n for i in range(2)]
    except NameError:
        b = "NE"
print(K.a, K.b)
  1. A. NE NE
  2. B. [0, 1, 2] [3, 3]
  3. C. [0, 1, 2] NE
  4. D. [0, 1, 2] []

Correct answer: C. [0, 1, 2] NE

The outermost iterable range(n) is evaluated in the class scope, so it works. But n used inside the comprehension body is looked up through the function-like scope, which skips the class body, so it raises NameError.

More Python Programming questions

Exams that ask this topic