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

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/[deleted] May 28 '23

This is it! Wow! Thank you so much for taking the time 🙏.

1

u/[deleted] May 28 '23

How do I type out my code like you did in your response?

1

u/[deleted] May 28 '23

There's a code block button in Reddit's editor. But because pasting always screws stuff up in "fancy mode", I instead go into "markdown mode" and add 4 spaces before each line of code (which I can do in my own text editor by highlighting everything and pressing tab). Use whichever method works for you.

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 👍

7

u/sepp2k May 27 '23

In your example, what would happen if you combined multiple calls of the addition function like this: addition(4, addition(5, 6))? And what would happen if you used return instead?

1

u/[deleted] May 28 '23

I guess the inner function would return type: None, and that would result in an error.

Thank you. I get it now.

5

u/[deleted] May 28 '23

print is how your functions talk to you. return is how they talk to the rest of your program.

1

u/[deleted] May 28 '23

Yeahhh. Thank you.

1

u/lukajda33 May 27 '23

You only use print if you want to show something to the user of the program, but usually you just want to calculate something and use it later in the program.

Lets say you had a program to calculate discount and tax for selling some product, you could have a function to calculate discount, another to calculate tax. You would return the result from the function in order to subtract or add it from total cost, but you would print only the final price to the user.

1

u/[deleted] May 28 '23

Brilliant! Thank you.

1

u/CraigAT May 28 '23

"return" passes the value back to whatever called the function. "print" just outputs the value to the screen.

Any Python.py for can be used as a module full of helpful functions or classes, having a "main" function is a defined way of allowing the file to be imported for the use of its functions (without running main) or the file to be run (executing the main function) as a program. Main functions are not necessary for a small script, but if the functions maybe useful elsewhere it could be considered useful to add a main function.

1

u/[deleted] May 28 '23

Thank you for your response.

What if there are multiple functions defined in main()? By calling main() won't one call on functions that are not needed?

1

u/CraigAT May 28 '23

The functions generally would be declared outside, but may (or may not) be called from within main().

https://realpython.com/python-main-function/#best-practices-for-python-main-functions

1

u/[deleted] May 28 '23

print formats its argument to a string and puts it to a file. It then returns None. Note: The default file is sys.stdout.

return puts its argument to the process that calls it.

They are very different in this way.

1

u/[deleted] May 28 '23

Print is for you to get the answer, return is if you want to keep using the output to do more stuff to the output.

1

u/[deleted] May 28 '23

Thank you.

1

u/Erdnussflipshow May 27 '23

print outputs text to the console.

return returns a value from a function, so that it can be used later on by other parts of you program.

For extremely basic projects, you can probably just use print but if at any point you need to use the values of a function for other things, you have to return those values from the function.

-1

u/ZelWinters1981 May 28 '23

Functions should have zero user interaction. No print statements, no direct access to the user. Think of functions like the back end of a shop, and the main loop as the user interface. Everything the user deals with is handled by the front end and then passed to and from the backend.

1

u/deadeye1982 May 28 '23

Functions should have zero user interaction. No print statements, no direct access to the user. Think of functions like the back end of a shop, and the main loop as the user interface. Everything the user deals with is handled by the front end and then passed to and from the backend.

You have to use functions for user-interactions, like print() or input().

The difference is, that print() returns None and input() returns a str.

Those functions do only one thing. Write bytes to stdout or read bytes from stdin.

The big difference is, that those functions do have side effects. Writing data to a terminal is the side effect of print(). Reading input from a terminal is the side effect of the function input().

Here is a bad example:

def square(n):
    result = n ** 2
    print(f"The square of {n} is {result}")
    return result

This function calculates the square of n and returns the result. The print function is the unwanted side effect. What if I want to reuse this function, but do not want the output. The answer is easy: Those functions would never be used.

Here is an example, where the side effect is wanted:

def ask_int(
    question,
    min_value=None,
    max_value=None,
    err_msg="An integer is required",
    err_msg_min="Integer is too small",
    err_msg_max="Integer is too big.",
    catch_sigint=False,
    catch_sigint_return=None,
):
    question = f"{question}: "
    while True:
        if catch_sigint:
            try:
                user_input = input(question)
            except KeyboardInterrupt:
                return catch_sigint_return
        else:
            user_input = input(question)

        try:
            # this may fail, if user_input
            # could not converted to an int
            user_int = int(user_input)
        except ValueError:
            print(err_msg)
            continue

        # this point is only reached, if there was no Exception
        # do this check only if min_value is not None
        if min_value is not None and user_int < min_value:
            print(err_msg_min)
            continue

        # here the same for max_value
        if max_value is not None and user_int > max_value:
            print(err_msg_max)
            continue

        # this point is reached, if the previous checks
        # were ok
        return user_int


cookies = ask_int(
    "How many cookies to you want to have?",
    min_value=0,
    max_value=10,
    catch_sigint=True,
    catch_sigint_return=0,
)

This function does have 3 side effects:

  • printing text to a terminal

  • read the line from terminal

  • listen for Signals: KeyboardInterrupt, if wanted

1

u/Not_A_Taco May 28 '23

Hard disagree on functions having no user interaction. There are tons of use cases where it would be optimal.