Exiting a Function
00:18 It’s supposed to have some effect on the overall execution of the program. One of the ways that it can do that is through side effects, as we talked about in the last lesson. More commonly, however, is it can return a value. We’ve asked it to do something, it has done that, and it is communicating back its result.
We do that with a
return statement, and the
return statement in Python does two things for us. One, it tells us we’re at the end of the function, or we don’t need to do any more processing within the function.
00:51 We’ve done everything we needed to do for this particular situation. And then we can also provide a value when we are done processing to communicate back to the calling environment the results of its task.
There are exceptions, and we’ll see that. So here in this example, we have a function
f() which is going to print
'foo', then on another line is going to print
'bar', and that’s all we want it to do, and we’re done. Now, if there’s no value to return, then sometimes we leave it off.
When Python executes a function that doesn’t have a
return statement, the return happens after the last statement that’s written. We call that “falling off the end.” In this example right here, this
return statement really wouldn’t be needed because there’s nothing else to worry about, it’s not giving us a value back, so we could leave that off and the function would behave the same way. Other times, we want to exit a function based on some type of test.
So, here’s a function that only wants to print a meaningful value of
x, something non-negative, but up to only
100. And so we’re going to do a couple tests. If we provide a negative number, then the evaluation of that
if statement will be
True and the function will return right there.
There’s nothing else to execute. If it gets past that, there’s another
if statement. We check to see if it’s bigger than
100, and if it’s bigger than
100, we don’t want to proceed any further either.
If it fails both of those, then we have a number between
100 inclusive and we print that value. Notice that there’s no
else in this. Because the function immediately stops executing with the
return statement, it will only get to the second
if statement provided the first one is
So, we could put
elif appropriately in here, but it’s not necessary, because the
return statements cause the function to stop executing at that very point. In the next lesson, you’ll learn a little bit more about the other use of a
return statement, and that’s returning data to the calling environment.
Become a Member to join the conversation.