Using Implicit Returns in Functions
00:00
Now let’s look at Python’s return
statement. The Python return
statement is a statement used inside a function or method to send the function’s result back to where the function was called.
00:12
It consists of the keyword return
followed by an optional return value. The return value can be any Python object, but remember—everything in Python is an object.
00:27
So you can return numbers, collection types—basically anything. If you don’t provide a return value, Python will return the value None
. If you don’t even have a return
statement, Python will still return None
.
00:47
These last two cases are examples of an implicit return value, and we’ll look at that first. Again, if you don’t provide a return value, or if you don’t even have a return
statement, None
will be used as the return value.
01:04
Keep in mind if you’re calling functions interactively, where normally you see the return value of a function—if the return value is None
, the interpreter won’t display it.
01:14
Python’s print()
function is an example of a function that returns None
, because we think of it as not actually returning a value at all.
01:24 If we just print something,
01:29 we see the output, but no return value. If we actually want to see the return value, let’s save the result of the function call to a variable.
01:46
We still see the output, but now we can see the value of return_value
by printing it.
01:56
As you can see, it is None
. Here’s another example. If a return
statement isn’t provided, then it too is going to have a return value of None
.
02:09
So if I define my function add_one()
, it takes a parameter, which we’ll call x
, and notice we don’t have a return
statement at all.
02:20
We’re going to create a variable result
to save what we get when we add 1
to x
. But that’s it. If I call add_one()
and provide it a number, we’re expecting 6
because within the function, 6
was computed, but we didn’t do anything with it. Again, if I want to see the return value, let’s save it.
02:55
This function didn’t return a value. It didn’t have a return
statement at all, and so Python used None
as its return value. Perhaps the author of this function meant to return the result, and we’ll take a look at how that’s done next when we look at explicit return
statements.
Become a Member to join the conversation.