Functions & Scope · Question 13 · Medium

Two counters are built from the same closure factory. What does the last line print?

def make_counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

c = make_counter()
c()
c()
d = make_counter()
print(c(), d())
  1. 3 4
  2. 1 1
  3. 3 3
  4. 3 1
Answer and explanation

Answer: D. 3 1

Explanation: Each call to make_counter creates a fresh n that only its own inc can see. c has already been called twice, so its third call returns 3, while d starts from its own n = 0 and returns 1.

Previous: A function is passed to another function as an argument. What does twice print… · Next: When Python looks up a name used inside a function, in which order does it…

Practise functions & scope

Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.

More functions & scope questions

More python practice

Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge