ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    def peek():
        return count
    return inc, peek
inc, peek = counter()
inc(); inc()
inc2, peek2 = counter()
inc2()
print(peek(), peek2(), inc())
  1. A. 3 1 3
  2. B. 2 1 1
  3. C. 2 1 3
  4. D. 0 0 3

Correct answer: C. 2 1 3

inc and peek of the same counter() call share one cell; the second call creates an independent cell. peek() sees 2 and peek2() sees 1; print evaluates arguments left to right, so the final inc() returns 3 after peek() already read 2.

More Python Programming questions

Exams that ask this topic