print vs. return#
These two look the same in Jupyter, but they do very different things:
printshows a value on the screen. The value is not saved anywhere.returnhands a value back to whatever called the function. This allows the possibility of it being stored and used later.
Here are two versions of the hello() function, one that uses print and one that uses return. Let’s look at the differences in how they behave.
def hello_print(name):
print("Hello, " + name + "!")
def hello_return(name):
return "Hello, " + name + "!"
1. results can look the same in jupyter#
hello_print("Zoe")
Hello, Zoe!
hello_return("Zoe")
'Hello, Zoe!'
2. trying to save the data#
a = hello_print("Zoe")
b = hello_return("Zoe")
Hello, Zoe!
Notice that hello_print still printed, even though we just wanted to store the result. Now let’s look at what actually got saved:
print("a is:", a) # hello_print()
print("b is:", b) # hello_return()
a is: None
b is: Hello, Zoe!
a is None, which is Python’s way of saying “nothing”. hello_print showed the greeting, but it never handed anything back, so there was nothing to store.
3. using the result#
What if we wanted to perform some change to the result? If you use print, it’s not possible, since the info is not stored in the environment.
b.upper() # works fine because b has a string stored inside
'HELLO, ZOE!'
a.upper() # throws an error because a is None, the string was not stored inside
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 a.upper() # throws an error because a is None, the string was not stored inside
AttributeError: 'NoneType' object has no attribute 'upper'
4. best practices#
Generally, we want to store the results of computations in variables so we can do further manipulations with them, so err on the side of return over print most times. If a function’s description (“docstring”) says “Returns a value that xyz”, definitely use the return keyword.
Print is mainly helpful for if you want to see the output of the result yourself just to check it, and you don’t need to perform any further changes. Still, it’s nice to store it in a variable and then call print on that variable (e.g., print(b)).
In the case of Homework 1 Problem 1, there was a wording that said “verify that when you run your new code cell it prints out xyz” but the docstring asked for you to return the value. Apologies for that (I can understand why many people used print instead because of this misleading wording) and we will change the wording for next time!