Skip to content Skip to sidebar Skip to footer

Is It Advisable To Use Print Statements In A Python Function Rather Than Return

Lets say I have the function: def function(a) c = a+b print(c) Is it advisable to use the print statement in the function to display output rather than placing a return st

Solution 1:

print and return solve two completely different problems. They appear to do the same thing when running trivial examples interactively, but they are completely different.

If you indeed just want to print a result, use print. If you need the result for further calculation, use return. It's relatively rare to use both, except during a debugging phase where the print statements help see what's going on if you don't use a debugger.

As a rule of thumb I think it's good to avoid adding print statement in functions, unless the explicit purpose of the function is to print something out.

In all other cases, a function should return a value. The function (or person) that calls the function can then decide to print it, write it to a file, pass it to another function, etc.

So the highlight of the question isnt the difference between print and return but rather if it is considered good style to use both in the same function and its possible impact on a program.

It's not good style, it's not bad style. There is no significant impact on the program other than the fact you end up printing a lot of stuff that may not need to be printed.

If you need the function to both print and return a value, it's perfectly acceptable. In general, this sort of thing is rarely done in programming. It goes back to the concept of what the function is designed to do. If it's designed to print, there's usually no point in returning a value, and if it's designed to return a value, there's usually no point in printing since the caller can print it if it wants.

Solution 2:

Well return and print are entirely two different processes.

Whereas print will display information to the user or through the console; and return is used for collecting data from a method that fulfills a certain purpose (to use later on throughout your program).

And to answer your question, I believe it would return the two values; since one prints the c variable itself, and the other returns the value c to present as well? Correct me if I'm wrong.

Post a Comment for "Is It Advisable To Use Print Statements In A Python Function Rather Than Return"