Closures Example in Python
Level 5219 keystrokes
This demonstrates closures where inner functions remember outer scope variables. Each counter maintains its own independent state.
Python code
# Factory function that creates counter functions1def make_counter(start=0): # count is captured by the inner function (closure)2 count = start # Inner function definition3 def counter(): # nonlocal allows modifying the outer variable4 nonlocal count # Increment count and return the new value5 count += 16 return count # Return the inner function (with its enclosed state)7 return counter8 # Create two independent counters9c1 = make_counter()10c2 = make_counter(10)11 # Each counter maintains its own count variable12print(f"c1: {c1()}, {c1()}, {c1()}")13print(f"c2: {c2()}, {c2()}")Output
c1: 1, 2, 3 c2: 11, 12
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 11)× 11{× 5}× 5=× 5:× 4"× 4_× 3,× 3+× 1