ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def counter():
    count = 0
    def step():
        nonlocal count
        count += 2
        return count
    return step
c1 = counter()
c2 = counter()
print(c1(), c1(), c2())
  1. A. 1 2 1
  2. B. 2 4 2
  3. C. 2 2 2
  4. D. 2 4 4

Correct answer: B. 2 4 2

Each call to counter creates its own count. c1 is called twice, giving 2 and then 4. c2 has its own count and returns 2 on the first call.

More Python Programming questions

Exams that ask this topic