In Python, the return statement exits a function and returns the specified value to the caller. Multiple return statements may exist in a function, but only the one that fulfils the specified condition first is executed.
The return keyword is one of the built-in keywords in Python which is also used for increasing readability and writing clear code in Python.
This tutorial will cover all the fundamental things you should know about return statements in Python.
Understanding the Python return Statement in Functions
- The Python return statement is used in a function to return something to the caller program.
- We can use the return statement inside a function only.
- In Python, every function returns something. If there are no return statements, then it returns None.
- If the return statement contains an expression, it’s evaluated first and then the value is returned.
- The return statement terminates the function execution.
- A function can have multiple return statements. When any of them is executed, the function terminates.
- A function can return multiple types of values.
- Python functions can return multiple values in a single return statement.
Syntax of Python return Statement
The syntax is straightforward, it consists of the keyword return followed by an expression.
Syntax:
return expression
Here the expression can be anything like an expression that can be evaluated to a value, the actual value, or even a function that we want to return to the caller.
Python return Statement Example
Let’s look at a simple example of a function that takes two numbers to perform a calculation and return the total to the caller.
def add(x, y):
total = x + y
return total
We can optimize the function by having the expression in the return statement.
def add(x, y):
return x + y
Let’s do a function call by passing two arguments, then print the result we got.
result = add(5, 3)
print(result)
Output:
8
See, here we got the sum, meaning the function successfully returned the total value.
Every Function in Python returns Something
Let’s see what is returned when a function doesn’t have a return statement.
>>> def foo():
... pass
...
>>>
>>> print(foo())
None
>>>
We got “None”, so if we didn’t pass a return statement and try to access the function value, by default it returns None.
Python return Statement without any Value
When the return statement has no value, the function returns None.
>>> def return_none():
... return
...
>>> print(return_none())
None
>>>
So, either you have used a return statement with no value, or there is no return statement, and the function returns None.
Python Functions can have Multiple return Statements
A function can have multiple returns, the one that satisfies the condition will be executed first and the function will exit.
Example:
def type_of_int(i):
if i % 2 == 0:
return 'even'
else:
return 'odd'
result = type_of_int(7)
print(result)
Output:
odd
Python Functions return Multiple Types of Values
Unlike other programming languages, Python functions are not restricted to returning a single type of value. If you look at the function definition, it doesn’t have any information about what it can return.
Example:
Let’s look at an example where the function will return numbers of values having multiple types.
def get_demo_data(object_type):
if 'str' == object_type:
return 'test'
elif 'tuple' == object_type:
return (1, 2, 3)
elif 'list' == object_type:
return [1, 2, 3]
elif 'dict' == object_type:
return {"1": 1, "2": 2, "3": 3}
else:
return None
print(get_demo_data('str')) Â # Output: 'test'
print(get_demo_data('tuple')) # Output: (1, 2, 3)
print(get_demo_data('list'))Â # Output: [1, 2, 3]
print(get_demo_data('dict'))Â # Output: {"1": 1, "2": 2, "3": 3}
print(get_demo_data('set')) Â # Output: None
Output:
test
(1, 2, 3)
[1, 2, 3]
{'1': 1, '2': 2, '3': 3}
None
Returning Multiple Values from a Function in a Single return Statement
A function can have multiple return values in a single statement. These values are separated by a comma and returned to the caller program as a tuple.
Example:
def return_multiple_values():
return 1, 2, 3
print(return_multiple_values())
print(type(return_multiple_values()))
Output:
(1, 2, 3)
<class 'tuple'>
Python return Statement with finally block
When the return statement is executed inside a try-except block, the finally block code is executed first before returning the value to the caller.
Example:
def hello():
try:
return 'hello try'
finally:
print('finally block')
def hello_new():
try:
raise TypeError
except TypeError as te:
return 'hello except'
finally:
print('finally block')
print(hello())
print(hello_new())
Output:
finally block
hello try
finally block
hello except
If the finally block has a return statement, then the earlier return statement gets ignored and the value from the finally block is returned.
def hello():
try:
return 'hello try'
finally:
print('finally block')
return 'hello from finally'
print(hello())
Output:
finally block
hello from finally
Summary
A return value in a function is the value that it sends back to the caller after it is finished executing. In other words, we can say that the return statement is the last statement that a function or method executes before it terminates. We can even return a function from another function. A function without a return statement or a return statement without a value returns None by default.
The return statement is certainly not an essential aspect of writing valuable functions because the main purpose of creating a function is to encapsulate a block of code in order to reuse that code. But it is the most important part of creating a function as it makes the function more feature-full and readable, so the next time you are creating a function, try using return instead of using the print statement.