Python function return Statement sends objects back to the caller code. These objects are known as the function’s return value.
def fun(): statements . . return [expression]
Note: The statements after the return statements are not executed.
Python function return
Simple example code Python Function Return Value.
def my_function(x):
return 100 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
Return list
def fun():
s = "Hello"
x = 20
return [s, x];
# Driver code
list1 = fun()
print(list1)
Output: [‘Hello’, 20]
Return Dictionary
def fun():
d = dict();
d['s'] = "Hello"
d['x'] = 20
return d
# Driver code
dict1 = fun()
print(dict1)
Output: {‘s’: ‘Hello’, ‘x’: 20}
Function returning another function
def create_adder(x):
def adder(y):
return x + y
return adder
add1 = create_adder(15)
print("The result is", add1(10))
# Returning different function
def outer(x):
return x * 10
def my_func():
# returning different function
return outer
# storing the function in res
res = my_func()
print("The result is:", res(10))
Comment if you have any doubts or suggestions on this Python function 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.