Returning vs Printing
It’s because they both do produce some type of result. These similarities are even more noticeable when working interactively. Let’s compare two functions that both provide the greeting
Notice, in this case, the quotes telling us that the return value is a string object. They didn’t appear in the print version, since we were telling Python to print a string and the
print() function doesn’t display the quotes. Well, that would suggest to us that the differences are even harder to detect when performing the same experiment with a number instead of a string.
Here we have functions that are printing and returning the number
42. This first function prints the number
42, and so when I call it, it carries out its one statement, which displays the output. Remember, it does return
None isn’t shown in the interpreter when that’s the return value.
So, the output’s identical, so does it really matter? Well, it matters when you’re writing scripts. Let’s take a look at this program. It defines a function to add two numbers, and then it calls that function to add
03:15 and call it interactively, because we’re in the interpreter, the interpreter is going to run the function, get the return value, and display it for us. However, if I run the entire program by importing the entire module,
This entire program was executed. The
add() function was defined and I performed the add operation on
2, but I didn’t have an output statement, so there is no output. I could even, if I wanted to, execute this from the command line.
And if I did this interactively by importing the entire module, the program is run and I do get the output of
4. Since in practice we do much more with scripts than we do interactively, we can’t count on the interpreter to display results for us, so be sure to use a print statement anytime you want something output.
Now that we understand the role of the
return statement, we can start exploring the different ways it can be used. First, we’ll look at how you can return multiple values in a single
Become a Member to join the conversation.