Return values and printed output

Lesson 11 of 54 · Python Foundations

Printing shows information to a person; returning supplies a value to the caller. Both can happen in a function, but they are different operations.

def show_total(amount):
    print(amount)

def make_total(amount):
    return amount

shown = show_total(7)
made = make_total(7)
print("shown:", shown)
print("made:", made)
7
shown: None
made: 7

The first 7 appears during show_total(7). Since the function reaches its end without a return value, the call returns None, stored in shown. The second function returns 7 without displaying it. A bare return also returns None.

A function can return related values as one tuple, a sequence of values. The caller can unpack them:

def parcel(length, width):
    perimeter = 2 * (length + width)
    area = length * width
    return perimeter, area

edge, surface = parcel(3, 4)
print(edge, surface)
14 12

The returned tuple is (14, 12); unpacking matches its values to edge and surface in order. The caller’s names need not match names inside the function.

Chapter index