Fix the Global Counter Bug
Beginner · Fix the bug · 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 lessonThis code tries to increment a global counter, but it crashes with an UnboundLocalError. Fix it so the output is:
1
2
3count = 0
def increment():
count = count + 1
print(count)
increment()
increment()
increment()
More Scope and Closures exercises
- Predict the Scope OutputBeginner
- Build a Greeting ClosureIntermediate
- Build a Counter with nonlocalIntermediate
- Build a Running Average ClosureAdvanced
All Python exercises · 50 practice problems · Functions quiz