Editor

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 lesson

This code tries to increment a global counter, but it crashes with an UnboundLocalError. Fix it so the output is:

1
2
3
count = 0
def increment():
count = count + 1
print(count)
increment()
increment()
increment()

More Scope and Closures exercises

All Python exercises · 50 practice problems · Functions quiz