Home:ALL Converter>Should function return print in Python?

Should function return print in Python?

Ask Time:2019-02-10T01:12:54         Author:Ala Cris

Json Formatter

I'm writing function which prepare data in csv file. I wonder what should it return. I thought that information in string for user will be good idea, but how should I do it?

return print('Some info')

Or just

return 'Some info'

And how about exceptions, I mean like above. When exception will end work of function should I return print('Some info') or just 'Some info'?

Author:Ala Cris,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54608583/should-function-return-print-in-python
tripleee :

No, return should return the result from the function, not the value of print (which is always None anyway).\n\nUsually, a function should not print anything at all. In order to make programs modular and reusable, you want to keep any user interaction in the calling code.\n\nFor example,\n\ndef fibonacci(n):\n fib = some calculation ...\n print(fib)\n return fib\n\nfibonacci(33)\n\n\nThis function has the side effect of printing the calculated value. But this means that you cannot calculate the value without also printing it. A common design principle from functional programming is that functions should not have side effects anyway. A better design is\n\ndef fibonacci(n):\n fib = some calculation ...\n return fib\n\nprint(fibonacci(33))\n\n\nExceptions are for situations where the code cannot perform the requested function. For example, you cannot calculate a negative Fibonacci number:\n\ndef fibonacci(n):\n if n < 0:\n raise ValueError('Cannot calculate negative Fibonacci number')\n fib = some calculation ...\n return fib\n\n\nYou could call this on arbitrary user input;\n\nwhile True:\n number = input('Give me a number: ')\n try:\n print('Fibonacci: ', fibonacci(int(number))\n except ValueError as e:\n print('Oops, try again; ', e)\n\n\nNotice how the except actually handles multiple error scenarios: if the use input isn't a number at all, int(number) will also raise a ValueError exception.",
2019-02-09T17:16:45
yy