Return or print?
A return value is a value like any other. You can print it, store it, calculate with it, compare it or give it to another function as an argument:
def to_minutes(hours, minutes):
return hours * 60 + minutes
def to_hours_text(minutes):
return str(minutes // 60) + " h " + str(minutes % 60) + " min"
film = to_minutes(1, 50)
series = 3 * to_minutes(0, 45)
print(film, series)
if film < series:
print("The film is shorter")
print(to_hours_text(film + series))
110 135
The film is shorter
4 h 5 minIn the last line, film + series is worked out first, its value 245 is given to to_hours_text, and the string it returns is given to print. Calls inside calls run from the inside out.
Return and print are different
A function that prints its result and a function that returns it can look alike when you try them out. Compare these two in the interpreter:
>>> def longer_print(a, b):
... if len(a) >= len(b):
... print(a)
... else:
... print(b)
...
>>> def longer(a, b):
... if len(a) >= len(b):
... return a
... return b
...
>>> longer_print("cat", "horse")
horse
>>> longer("cat", "horse")
'horse'
>>> longer("cat", "horse").upper()
'HORSE'
>>> result = longer_print("cat", "horse")
horse
>>> print(result)
NoneThe interpreter shows the difference: horse without quotes is text that the function printed, while 'horse' with quotes is a value that it returned. You can go on working with the returned value, like calling upper on it. The printed text is only on the screen: the code that called longer_print gets nothing back.
A function that ends without a return gives back the special value None, which means "no value". Using None as if it were a string or a number stops the program:
def longer_print(a, b):
if len(a) >= len(b):
print(a)
else:
print(b)
word = longer_print("cat", "horse")
print(len(word))
horseTraceback (most recent call last):
File "main.py", line 9, in <module>
print(len(word))
~~~^^^^^^
TypeError: object of type 'NoneType' has no len()NoneType is the type of None. When you see it in an error message, a function probably printed something instead of returning it, or forgot its return.
Returning is usually the better choice, because the result can still be used in any way, printing included. That's why the checks of a task that asks for a return value fail when your function prints the right text instead of returning it.