Tuesday, July 28, 2020

Returned value(s) from function

Return:

with the help of return keyword, the function can terminate and provide the obtained(calculated) result back to the caller(i.e. the portion of the code where the function was called). the return keyword can either empty or absent in case of a void function else provide with value(s) in case of non-void function.Note: within the function whenever the return keyword is encontered, the function will terminate, so it can be used to halt function based on some condition.

In [3]:
def val(a,b):
    if b==0:
        return
    else:
        return a/b
In [4]:
print(val(5,2)) # IN THIS CASE THE RETURN KEYWORD IS USED TO GET DIVISION RESULT
2.5
In [6]:
print(val(5,0)) # IN THIS CASE THE RETURN KEYWORD IS USED TO TERMINATE THE FUNCTION
None

Void Function:


These are the function that do not return any value and only prints the value. Note: in these type either keyword return is not used or if used then without any value or expression.Example:

In [1]:
def su(a,b,c):
    print(a+b+c)

su(10,20,30)
60

now the above function does gives us the sum of three numbers but we can't take that number and do some more operation on it. So when we need to get hold of the value and do some operation with then we must use return keyword.

Non-Void Function:

These function return the value computed by the function to the caller. The value being returned can be one of either A Literal, A Variable or An Expression.Example

In [1]:
def ad1(a,b):
    return a+b    #This is returning an expression to the caller
In [2]:
def ad2(a,b):
    sm=a+b
    return sm   #This is returning an varibale to the caller
In [3]:
def val():
    return 10  #This is returning a Literal(in this case integer literal)

Note: if we don't assign the function to an variable then the value returned doesn't gets stored any where, python will not through any error but the returned value is completely wasted

Function returning multiple values


python allows a function to return multiple values. Following points to be taken care of when handling function that return multiple values

  • The multiple values/expression to be returned must be seperated by comma
  • The values/expression returned must be stored in a tuple or directly unpacked in variables

In [7]:
def arithmetic(a,b):
    return a+b,a*b,a-b   #returning multiple values(i.e. expression)
In [8]:
tp=arithmetic(5,2)
print(tp)
print(type(tp))
(7, 10, 3)
<class 'tuple'>

in the above example tp is a tuple and is used to store the multiple values returned by the function.

In [10]:
val1,val2,val3=arithmetic(5,2) #the values are unpacked into 3 variables
print(val1,val2,val3,sep="\n")
7
10
3

References:

  • computer science with python sumita arora
Share: