Last Updated On By Khizer Ali
The return statement in Python is a unique statement that we can use to end the function call’s execution and send the result to the caller.
There will be no execution of any statement after the return statement. If we declare the return statement is without any expression, it will return the unique value None.
We can define a return statement using the return keyword, and the return value of a Python function can be any Python object.
Table of Contents
Def function():
statements
return [experation]
In this program we will add two integers and check the Boolean value for condition true or false.
def addition(a, b):
return a + b
def boolean(a):
return bool(a)
res = addition(16, 75)
print("Result of addition function is {}".format(res))
res = boolean(16<75)
print("\nResult of boolean function is {}".format(res))
There are two types of return statement:
An explicit return statement terminates the function execution immediately and send the returned value to the caller.
def get_even(numbers):
even_nums = [num for num in numbers if not num % 2]
return even_nums
e_n = get_even([1,2,4,3,6,7])
print(e_n)
In the above example, we defined a function and passed an argument inside it. Inside the function, we created a variable to get even numbers from the list, which we pass as the function argument using the for-in loop. Finally, we can see that our explicitly defined return statement is giving us the desired results.
What if we don’t define return statements explicitly? The function will return the value implicitly; there is a default value for the implicit return statement, and that value is None.
def get_even(numbers):
even_nums = [num for num in numbers if not num % 2]
print(even_nums)
e_n = get_even([1,2,4,3,6,7])
print(e_n)
In the above example, we didn’t define the return statement explicitly, so the function is returning a default implicit return statement value that is None.
In python, from a single function, we can return multiple values. To understand this, check the example below.
class Test:
def __init__(self):
self.str = "Code Leaks"
self.x = 75
def fun():
return Test()
t = fun()
print(t.str)
print(t.x)
def fun():
str = "Code Leaks"
x = 75
return str, x;
str, x = fun()
print(str)
print(x)
def fun():
str = "Code Leaks"
x = 75
return [str, x];
list = fun()
print(list)
def fun():
d = dict();
d['str'] = "Code Leaks"
d['x'] = 75
return d
d = fun()
print(d)
def create_adder(x):
def adder(y):
return x + y
return adder
add_15 = create_adder(75)
print("The result is", add_15(16))
def outer(x):
return x * 10
def my_func():
return outer
res = my_func()
print("\nThe result is:", res(37))