Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a function print a string or return it?

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.

like image 600
Neghtasro Avatar asked Jun 20 '12 20:06

Neghtasro


People also ask

Does the print function return a string?

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.

Should I use return or print in Python?

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.

Can a function return a string?

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.

Does print () always return string Python?

In Python 3, print , a function, always returns None .


1 Answers

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.

like image 62
Mark Byers Avatar answered Sep 17 '22 15:09

Mark Byers