First thing to note is that, return
and print
are statements, not functions.
Basic Explanation
Print
only shows the human user a string representing what is going on inside the computer. Though the computer cannot make use of that printing that is why return
is a function that gives back a value. With this value it is often unseen by the human user but it can be used by the computer in further functions
Expansive Explanation
Print is like a console.log version of JavaScript. It is mainly for the user to see how it works. It is very useful to understand how a program works and where you can start debugging to check various values in a program without interrupting the program.
return
is the main way that helps a function return a value. All functions will return a value, and if there is no return
statement (or yield
), it will return None
. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user.
Consider these two programs:
def function_prints():
print "I printed"def function_returns():
return "I returned"f1 = function_prints()
f2 = function_returns()
print "Now let us see what the values of f1 and f2 are"
print f1
print f2
The following is what will be seen in the console:
"I printed"
"Lets see what the values of f1 and f2 are"
None
"I returned"
When function_prints
ran, it automatically printed to the console "I printed"
. However, the value stored in f1
is None
because that function had no return
statement.
When function_returns
ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2
. When we printed f2
at the end of the code, we saw "I returned"
Now let us try another example:
def print_number(num):
print numdef return_number(num):
return numdef add_three(num):
return num + 3f1 = print_number(7)
f2 = return_number(2)
print f1
print f2
f3 = add_three(f2)
print f3
f4 = add_three(f1)
print f4
In this example, we pass the results of a function to another function. Let us see what the console will say
7
None
2
5
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Notice that we got an error when we tried to pass f1
to add_three
because f1
had a value of None
, even though it had printed out the correct number. This is why it is important to return
values and not print
them (except when we want to know what the value is).