Build a Greeting Closure
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_greeter that takes a greeting string as an argument and returns a new function. The returned function should take a name argument and print the greeting with the name.
For example:
hello = make_greeter("Hello")
hello("World")Should print: Hello, World!
The test will call:
hi = make_greeter("Hi")
hi("Alice")
hi("Bob")Expected output:
Hi, Alice!
Hi, Bob!def make_greeter(greeting):
# Return a function that prints greeting + name
pass
hi = make_greeter("Hi")
hi("Alice")
hi("Bob")
More Scope and Closures exercises
- Predict the Scope OutputBeginner
- Fix the Global Counter BugBeginner
- Build a Counter with nonlocalIntermediate
- Build a Running Average ClosureAdvanced
All Python exercises · 50 practice problems · Functions quiz