Return Statement In Python
Python Return Statement
The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and it returns nothing when there is no expression passed to return statement. There can be multiple return statements in a function but only a single statement is called for any specified invocation of the function.
We can see a return statement is placed at the end of the block of the function for returning the final output of the execution of all statements inside the function. Also, it can be seen earlier in the block of the function for stopping the execution of all consequent statements in the block. The execution of the program at the caller is quickly restarted with a return statement. It returns none when no value is specified.
Example 1:
# Python code for
#demonstrating use of return statement
def myfunc(a, b):
add = a + b
sub = a - b
mul = a * b
div = a % b
return(add, sub, mul, div)
# Getting return value and printing the output
output = myfunc(49,45)
print("Addition: ", output[0])
print("Subtraction: ", output[0])
print("Multiplication: ", output[0])
print("Division: ", output[0])
Output:
Addition: 94
Subtraction: 4
Multiplication: 2205
Division: 1.08
Explanation: In the above example, we returned the sum of addition, substraction, multiplication, and division by using the return statement.
Example 2:
# Python code for
#demonstrating use of return statement
class check:
def __init__(self):
self.str = "Tutorial and examples"
self.x = "Kaushal"
# Object of test will be returned by this function
def fun():
return check()
# Driver code for checking the above method
t = fun()
print(t.str)
print(t.x)
Output:
Tutorial and examples
Kaushal
Explanation: In the above example, we have seen the use of return statement. The return statement can return all types of values and it returns nothing when there is no expression passed to return statement.
Conclusion
In the above article, we have discussed the return statement in Python. Also, we have understood the concepts of return statement and know how to use it in our Python programs.