What does the following code output? def make_counter(): count = 0 def increment(n=1): nonlocal count count += n return count def reset(): nonlocal count count = 0 increment.reset = reset return increment c = make_counter() c(3) c(2) c.reset() print(c())

Python Professional Hard

Python Professional — Hard

What does the following code output? def make_counter(): count = 0 def increment(n=1): nonlocal count count += n return count def reset(): nonlocal count count = 0 increment.reset = reset return increment c = make_counter() c(3) c(2) c.reset() print(c())

Key points

  • The counter starts at 0 and is incremented by 3 and then 2.
  • The reset function sets the counter back to 0.
  • The final output is the result of the last increment operation.

Ready to go further?

Related questions