Build a Running Average Closure
Advanced · 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_averager that returns a function. Each time the returned function is called with a number, it should print the running average of all numbers seen so far.
The running average is the sum of all numbers divided by the count.
The test will call:
avg = make_averager()
avg(10)
avg(20)
avg(30)Expected output:
10.0
15.0
20.0Hint: the averager needs to remember both the total sum and the count of numbers.
More Scope and Closures exercises
- Predict the Scope OutputBeginner
- Fix the Global Counter BugBeginner
- Build a Greeting ClosureIntermediate
- Build a Counter with nonlocalIntermediate
All Python exercises · 50 practice problems · Functions quiz