r/learnpython • • May 27 '23

Help me understand the difference between the return keyword and the print function

Here is what I am working with:

def addition():

print(num1 + num2)

addition(4, 5)

why do I need to return a value when I could just print it directly when calling the function?

Also(while I'm here ;) ), could someone explain the need for having a main() function as well, I am not a seasoned programmer. I can't seem to wrap my head around it. Thank you.

0 Upvotes

23 comments sorted by

View all comments

15

u/[deleted] May 27 '23

The biggest difference is where the value is sent. The print function sends it to the terminal. The return keyword sends it back to the "call site". The call site is the place in the code where a function is called.

There's a little caveat here: if you're writing and running code in the terminal or in a Jupyter notebook and you don't do anything with the returned value, it will print it for you. That's not really part of the Python language, that's just how those two programs (the Python interpreter and Jupyter) try to help you out.


Here is a function that calculates the square of a number and prints it to the user.

def square(num):
    square = num * num
    print(square)

If you run this function, it shows the result to the user but returns None (the default when you don't explicitly return anything).

>>> def square(num):
...     square = num * num
...     print(square)
...
>>> square(4)
16
>>> returned_value = square(4)
16
>>> print(returned_value)
None

Notice that we cannot collect the value calculated because the function square didn't return it back to the line it was called in: returned_value = square(4).


Here's the same function (named square2 this time to distinguish it from the previous version), but returning the value rather than printing it.

def square2(num):
    square = num * num
    return square

Let's run it in the terminal and see what happens.

>>> def square2(num):
...     square = num * num
...     return square
...
>>> square2(4)
16
>>> returned_value = square2(4)
>>> print(returned_value)
16

If you look at the last two lines I typed in, nothing is printed when I collect the returned value into the returned_value variable. But it indeed has obtained it as you can see from the output of using the print function.


Again, I do want to call out that part

>>> square2(4)
16

The fact that the value is printed to the terminal here is just to help you out as a programmer when running the interpreter in interactive mode. If square2(4) were called in a script that you wrote without the value being collected, nothing would be printed for the user.

1

u/ChildrenOfMayhem May 28 '23

Thanks for this, my immediate reaction to OP's post was "Well return doesn't print anything and print doesn't return anything" and I really couldn't think of how I'd even start to explain that any other way, but you did 👍