Nested Functions
Lesson 2 of 12 in Coddy's Python Decorators course.
Before we dive into decorators, we need to understand a few important concepts related to Python functions.
In Python, we can include one function inside another, also known as a nested function.
For example,
def outer_function():
print("This is the outer function.")
def inner_function():
print("This is the inner function.")
inner_function()
In this example, outer_function contains a nested function called inner_function.
When outer_function is called, it will first print "This is the outer function." and then call inner_function. inner_function will then print "This is the inner function."
Note that inner_function can only be called from within outer_function.
If you try to call inner_function outside of outer_function, you will get a NameError saying that inner_function is not defined.
Challenge
EasyWrite a function called greeting_generator that takes a name as an argument and returns a greeting message that includes the name.
The greeting message should be generated by a nested function called get_greeting, which takes the name as an argument and returns a string that says "Hello, [name]!".
Here's an example of how the function should work:
>>> greeting = greeting_generator("Alice")
>>> greeting
"Hello, Alice!"
>>> greeting = greeting_generator("Bob")
>>> greeting
"Hello, Bob!"
Constraints
- You must use a nested function called
get_greetingto generate the greeting message. - The greeting message must include the name passed to
greeting_generator.
Try it yourself