Results when using both print and return within a function

When defining a function, is there a difference whether I use print() or return?
I’m a little confused as to why sometimes a function will use both print() and return together.

For example:

def lots_of_math(a,b,c,d):
first = a+b
second = c-d
third = first*second
print(first)
print(second)
print(third)
return third%a

Why is not print(third%a)?

Yes, the greatest difference being retention of the return value for further use by the program.

def foo(bar):
    print (bar * 2)

When the function finishes executing, the value of bar * 2 is lost.

def foo(bar):
    return bar * 2

double_bar = foo(21)
print (double_bar)    # 42

If the intention is to print, and not retain the outcome, then that’s up to the writer. You will find that we use return much more than print in a larger project. Functions are utilities for handling repeated tasks. Often some functions rely on the output of other functions, and the way this is done is with return values being passed back to the caller.

1 Like

Short answer:

  • We print() values that we want to see on the screen
  • We return values that Python needs to use: to assign to a variable, for instance, or to send to another function as an argument.

so if I defined foo(bar) using print, I wouldn’t be able to call back this function later?

In other words, if

def foo(bar):
print (bar * 2)

and bar = 2

the output would =4 only once?

I cannot use the function of foo(bar) again?

We can call a function as many times as we need. That is what makes functions so useful. For each call argument we get a predictable outcome.

Say we have a program that computes the number of 9" x 9" tiles we need to cover a given area in square feet…

def tile_count_by_area(width_count, length_count):
    return width_count * length_count

def tile_count_by_length(feet):
    return 12 * feet // 9

room_width_in_feet = 15
room_length_in_feet = 21
width_count = tile_count_by_length(room_width_in_feet)
length_count = tile_count_by_length(room_length_in_feet)

total_tile_count = tile_count_by_area(width_count, length_count)
print (f"{room_width_in_feet} X {room_length_in_feet} needs {total_tile_count} tiles.")

# 15 X 21 needs 560 tiles.
1 Like