Returning Functions From Functions
This lesson covers how to return functions from functions.
The code example in the lesson uses a function called
parent() that contains two inner functions that return a string of text:
def parent(num): def first_child(): return "Hi, I am Emma" def second_child(): return "Call me Liam" if num == 1: return first_child else: return second_child
You’ll see how to access these inner functions and assign them to variables.
If functions can be defined inside of other functions, can a function also be returned from a function? Sure. It’s time for another example. Continuing in this idea of functions inside of functions, let me have you make a new one. This one will be named
parent() also, so start off with
def parent(). This time you’ll have an argument of
num—it will be used for selecting the child. Right away in the statement, you’re going to start with defining a new function named
first_child() that doesn’t take any arguments, and for its statement, you’ll have it return a string of text that says
"Hi, I am Emma".
Then, define a
second_child() function. For that function, I’ll have you return text that says
"Call me Liam". And last, before we return out of our main statement, returning from the function itself, we’ll set up a little condition.
If the argument
num is equal to
1, return the function
first_child—not calling it, but simply returning the function itself.
else—in all other cases—return the other child,
second_child. Again, not calling it, just simply returning it as a function. And close the statement.
That means if
num is set to
1, it should return
first_child. Okay. It looks like nothing happened. Well, let’s try a second one. Let’s set up another variable,
second, and pass the argument of
2. So, what are these? We’ll look at
first by itself—not call it, just type in the name and Return.
So these two variables
second are actual functions that are referencing—from the
parent() function, inside of the scope of the
first_child function or the
Become a Member to join the conversation.