The return keyword is used at the end of the function when there is a need to send back the result of the function back to the caller. Software programming is not about printing results all the time. There are some calculations that must be performed behind the scene, hidden from the users. These values are further used in calculations to get the final output that the users desire. The value obtained from the return statement can be assigned to a variable and used further for calculations.
Look at the code given in the following box. The function adding_numbers() adds three numbers and returns the result which is is assigned to variable x. The value of x is then displayed as output.
def adding_numbers(num1, num2, num3):
print('Have to add three numbers')
print('First Number = {}'.format(num1))
print('Second Number = {}'.format(num2))
print('Third Number = {}'.format(num3))
return num1 + num2 + num3
x = adding_numbers(10, 20, 30)
print('The function returned a value of {}'.format(x))
Output:
Have to add three numbers
First Number = 10
Second Number = 20
Third Number = 30
The function returned a value of 60
Thus we can say that:
1. A return statement exits the function. It is the last statement of a function and any statement coming after that will not be executed.
2. When a function is not returning a value explicitly that means that indirectly or implicitly it is returning a value of None.
3. If a function has to return more than one value, then all the values will be returned as a tuple.
As an exercise make some more programs and use the return statement in them.
0 comments:
Post a Comment