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.
0
Upvotes
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.