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.
def val(a,b):
if b==0:
return
else:
return a/b
print(val(5,2)) # IN THIS CASE THE RETURN KEYWORD IS USED TO GET DIVISION RESULT
print(val(5,0)) # IN THIS CASE THE RETURN KEYWORD IS USED TO TERMINATE THE FUNCTION
def su(a,b,c):
print(a+b+c)
su(10,20,30)
def ad1(a,b):
return a+b #This is returning an expression to the caller
def ad2(a,b):
sm=a+b
return sm #This is returning an varibale to the caller
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
def arithmetic(a,b):
return a+b,a*b,a-b #returning multiple values(i.e. expression)
tp=arithmetic(5,2)
print(tp)
print(type(tp))
in the above example tp is a tuple and is used to store the multiple values returned by the function.
val1,val2,val3=arithmetic(5,2) #the values are unpacked into 3 variables
print(val1,val2,val3,sep="\n")
References:
- computer science with python sumita arora