r/learnpython • u/[deleted] • 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.
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
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
May 28 '23
print is how your functions talk to you. return is how they talk to the rest of your program.
1
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
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
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
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
1
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
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()orinput().The difference is, that
print()returnsNoneandinput()returns astr.Those functions do only one thing. Write
bytestostdoutor read bytes fromstdin.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 functioninput().Here is a bad example:
def square(n): result = n ** 2 print(f"The square of {n} is {result}") return resultThis function calculates the square of
nand 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.
15
u/[deleted] May 27 '23
The biggest difference is where the value is sent. The
printfunction sends it to the terminal. Thereturnkeyword 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.
If you run this function, it shows the result to the user but returns
None(the default when you don't explicitly return anything).Notice that we cannot collect the value calculated because the function
squaredidn't return it back to the line it was called in:returned_value = square(4).Here's the same function (named
square2this time to distinguish it from the previous version), but returning the value rather than printing it.Let's run it in the terminal and see what happens.
If you look at the last two lines I typed in, nothing is printed when I collect the returned value into the
returned_valuevariable. But it indeed has obtained it as you can see from the output of using theprintfunction.Again, I do want to call out that part
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.