Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Inner Functions

In this lesson, you’ll see how to define Python functions inside of other functions.

00:00 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 parent().

00:17 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 parent().

00:28 It’s named 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".

00:48 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 first_child().

01:06 So, what will happen when you call parent()? First off, as it walks down through the statement, it prints "the parent() function".

01:17 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.

01:42 What if you tried to access first_child by typing its name? It says […] 'first_child' is not defined. And second_child?

01:56 Same thing. So those objects are not defined within the scope outside of this function.

02:05 They’re only inside parent().

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.

dwalsh on June 9, 2020

So functions can be incepted.

Become a Member to join the conversation.