Why should I use return in python functions when I can use print() and it gives me the same result? Is there any specific use cases or there's something that I can't understand? I'll be glad if you describe the answer simple and clear:)
Using print:
def test(var):
print(var)
test("Hello World!")
Result: Hello World!
Using Return
def test(var):
Return var
print(test("Hello World!"))
Result:Hello World!
CodePudding user response:
The use case is that it is not always, rather rarely, a matter of outputting the result of a function to the console.
Imagine having a function to square a number:
def square(number):
return number * number
If you would do it with print()
you just output the result to the console, nothing more.
Using return
you have the result returned to where the function call came from so you can proceed using it for something.
For example now you want to add two squared numbers like: a² b²
Using the function we build earlier we could do:
number = square(a) square(b)
This would not be possible if the square function would simply output the result to the console since then there is nothing returned we could add together.
And yes, i know you don't need a function to square a number, that's just an example to explain it.
CodePudding user response:
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).