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 functions
1def make_counter(start=0):
# count is captured by the inner function (closure)
2 count = start
# Inner function definition
3 def counter():
# nonlocal allows modifying the outer variable
4 nonlocal count
# Increment count and return the new value
5 count += 1
6 return count
# Return the inner function (with its enclosed state)
7 return counter
8
# Create two independent counters
9c1 = make_counter()
10c2 = make_counter(10)
11
# Each counter maintains its own count variable
12print(f"c1: {c1()}, {c1()}, {c1()}")
13print(f"c2: {c2()}, {c2()}")

Output

c1: 1, 2, 3
c2: 11, 12
Practice typing this code

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

More Python examples at level 5

← Python typing practice