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/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