I'm writing a Python script, and it needs to print a line to console. Simple enough, but I can't remember (or decide) whether the accepted practice is to print in the function, for example:
def exclaim(a):
print (a + '!')
or have it return a string, like:
def exclaim(a):
return (a + '!')
and then print in the main script. I can make an argument for either method. Is there a generally accepted way to do this or is it up to preference?
EDIT: To clarify, this isn't the function I'm working with. I don't feel comfortable posting the code here, so I wrote those functions as an oversimplified example.
print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.
Use print when you want to show a value to a human. return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string.
In Python 3, print , a function, always returns None .
Normally a function should generate and return its output and let the caller decide what to do with it.
If you print the result directly in the function then it's difficult to reuse the function to do something else, and it's difficult to test as you have to intercept stdout rather than just testing the return value.
However in this trivial example it hardly seems necessary to either reuse or test the function, or even to have the function at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With