The return statement should be used in scenarios where you want to process the results which are the output of your function. An example of this is the function getEvens which tries to return all the even numbers in a given list:
def getEvens(l):
"""
The function takes a list as input and returns only even no.s of the list.
"""
# Check if all elements are integers
for i in l:
if type(i) != int:
return None # return None if the list is invalid
return [i for i in l if i%2 == 0] # return filtered list
Here in the driver code, we are passing the input list to the getEvens function, depending upon the value function returns we output a customized message.
def main(l):
functionOutput = getEvens(l) # pass the input list to the getEvens function
if functionOutput is None:
# As the function returned none, the input validation failed
print("Input list is invalid! Accepting only integers.")
else:
# function has returned some other value except None, so print the output
print("Filtered List is", functionOutput)
If we consider some scenarios now
Case 1:
l = [1, 7, 8, 4, 19, 34]
main(l)
# output is: Filtered List is [8, 4, 34]
Case 2:
l = [1.05, 7, 8, 4.0, 19, 34]
main(l)
# output is: Input list is invalid! Accepting only integers.
Case 3:
l = [1, 7, 8, 4, "19", 34]
main(l)
# output is: Input list is invalid! Accepting only integers.
So the main thing to look out for here is we are using the output of the function for later processing, in this case taking a decision to customize the output message. A similar use-case is of function chaining where the output of 1st function will be an input to the 2nd one, and 2nd output will be input to the 3rd (this cycle may continue longer ;P).