Build a Counter with nonlocal
Intermediate · Write the code · from Python Variable Scope, Closures, and the LEGB Rule
From the lesson: Python Variable Scope, Closures, and the LEGB Rule
Imagine a house with several rooms. Each room has its own set of objects - a lamp on the bedroom nightstand, a knife in the kitchen drawer. You can use items in the room you're standing in, and you can walk to the hallway to grab something shared.
Read the lessonWrite a function called make_counter that takes a start value and returns a function. Each time the returned function is called, it should print the current count and then increment it by 1.
The test will call:
c = make_counter(1)
c()
c()
c()Expected output:
1
2
3def make_counter(start):
# Your code here
pass
c = make_counter(1)
c()
c()
c()
More Scope and Closures exercises
- Predict the Scope OutputBeginner
- Fix the Global Counter BugBeginner
- Build a Greeting ClosureIntermediate
- Build a Running Average ClosureAdvanced
All Python exercises · 50 practice problems · Functions quiz