Return Values versus print()
Core idea
return expression ends the current function call and supplies a value to the caller. print() displays text and returns None, the special value representing absence of a meaningful result. Returning a value allows further calculations without printing anything.
def discount(price): return price - 2
amount = discount(9)print(amount * 3)The caller multiplies the returned 7 by 3.
Observe implicit None
def show_count(count): print(count)
result = show_count(4)print(result)The first line is a side effect of printing; falling off the end returns None.
Return early
def usable(count): if count < 0: return 0 return count
print(usable(-3))print(usable(5))For negative input the first return ends the call before the second return.
Common mistake
Do not replace return total with print(total) when a caller needs the total. A bare return also returns None.
Practice
Write a function returning the larger of zero and a supplied balance using if. Store the result and print it in the caller.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Return and display
Check your understanding of return and print.
What is printed?
def size(n): return n + 1print(size(3) * 3)What is printed?
def show(): print("Hi")print(show())What is printed?
def safe(n): if n < 0: return 0 return nprint(safe(-2))Which statement makes a value available for the caller to multiply?