In this lesson, you’ll see how to define Python functions inside of other functions.
Next, I want to show you inner functions. Is it possible to define functions inside of other functions? Sure! Let me show you an example. To start, I’ll have you define a function named
The first part of the statement,
parent() is going to
print("Printing from the parent() function"). Next, you need to indent over and define another function inside of
first_child(). So far, all of these functions don’t take any arguments. I made a small mistake there, pressing Return a little early, but it will work the same. So for this function,
first_child(), it will have a print statement saying
"Printing from the first_child() function".
And now I’ll have you define a
second_child() function. It will look similar,
"Printing from the second_child()". Now, before you leave the statement and end this function, I’ll have you call
second_child() with parentheses—so we’ll call it—and then call
So, what will happen when you call
parent()? First off, as it walks down through the statement, it prints
"the parent() function".
Then it defines
first_child() and defines
second_child(), setting both of them up. Then, it actually will print
"the second_child() function", and print
"the first_child() function" last. I know this is a very simple example, but you can get the concept that even elaborate functions could be defined inside of other functions.
What if you tried to access
first_child by typing its name? It says […]
'first_child' is not defined. And
01:56 Same thing. So those objects are not defined within the scope outside of this function.
They’re only inside
02:10 Both of them reside inside of there, locally. That’s what the next video is about. What if you wanted to access functions that live inside another function?
02:22 Can you return them out of an existing parent function? Get them out of the local scope, and be usable outside of it? That’s what I’ll show you next.
Become a Member to join the conversation.
dwalsh on June 9, 2020
So functions can be incepted.