ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
class C:
    k = 10
    try:
        a = [k + x for x in range(3)]
    except NameError:
        a = 'NameError'
print(C.a)
  1. A. NameError
  2. B. [10, 11, 12]
  3. C. [0, 1, 2]
  4. D. TypeError

Correct answer: A. NameError

A comprehension has its own scope, and it cannot see names from the class body. So k is undefined inside the list comprehension and raises NameError.

More Python Programming questions

Exams that ask this topic