← Intro to programming with Python
return vs print
Send an answer back so the rest of the program can use it.
print() shows a value to a PERSON. return hands a value back to the PROGRAM, so it can be stored, compared or used in more math. Think of a calculator: pressing = shows the answer, but return is like the calculator passing the answer straight into the next calculation. Most useful functions return their result and let the caller decide whether to print it. When Python reaches return, the function ends immediately.
def add_tax(price):
return round(price * 1.1, 2)
total = add_tax(20) + add_tax(5)
print(total) # 27.5
print(add_tax(9.99)) # 10.99Because add_tax returns its answer, we can add two results together. A function that only printed could not be used like that.
Common mistake: printing inside a function and then trying to use the result. A function with no return gives back None, so total = show_tax(20) stores None, and None + 5 is a TypeError.
Code after a return (in the same block) never runs, because return ends the function.
A function can return True or False, which makes it handy inside an if: if is_even(n):