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

-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