For more information on topics covered in this lesson, check out these resources:
Using Explicit Returns in Functions
Now let’s look at explicit
return statements. When a Python function executes an explicit
return statement, the function immediately ends its execution and sends the return value back to the calling environment. As previously mentioned, a
return statement begins with the keyword
return, followed by an optional return value. For example, in this simple function, the statement
return 42 means the number
42 will be returned back to where the function was called.
I get the number
42 back. And since we are in the interpreter, that number is displayed. The return value for a function can be used in any expression, so I can save it to a variable or just use it directly from the function call.
return statements only makes sense inside the body of a function. And recall that methods—regular methods, class methods, static methods—are just functions within the context of a class or an object, so anything you’ve seen here about functions applies to methods as well.
This function uses a Python syntax called list comprehension. It’s a way to simplify a common
if nested coding structure, which filters a list, looking for those elements meeting a specific condition.
Real Python has many resources for list comprehension, some of which are linked below. If we take a look at the function more closely, we see that it takes an argument, a list of numbers called
The return value can be any valid Python expression. We could simplify the
get_even() method by just returning the result from the list comprehension without saving it to a different variable name.
05:48 Here’s another example where I can use Python’s sum and length functions to write a new function to find the mean of a collection of numbers. Just returning the expression, we’re going to take the sum divided by the length.
Become a Member to join the conversation.