The return statement is used at end of the Python function to return some value or end the execution of the function call. No code will be executed after the return statement in the function.
def fun():
statements
.
.
return retrun_value
Note: If the return statement is doesn’t have any expression, then the None is returned.
Examples return statements in Python
Simple example code to demonstrate return statement in Python.
Addition function simple return statement
The function will take 2 parameters and return the addition of values.
def add(a, b):
return a + b
# calling function
res = add(2, 3)
print(res)
Output:
Return Multiple Values
The function will return multiple values in a tuple. A Tuple is a comma-separated sequence of items.
Read more: Python function returns multiple values ( Return list, dictionary, etc.)
def cal(a, b):
return a + b, a * b, a - b
# calling function
res = cal(2, 3)
print(res)
Output: (5, 6, -1)
Function returning another function
Python program to illustrate functions can return another function.
def outer(x):
return x * 10
def first_func():
# returning function
return outer
# storing the function in var
res = first_func()
print(res(10))
Output: 100
Do comment if you have any doubts and suggestions on this Python return topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.