0
Why nesting of function within print() fn. is printing 'none' in output
----------------- def mf(): print('rt\n'*2) print(mf()) Output:- rt rt none ---------------v/s def mf(): print('rt\n'*2) mf() Output:- rt rt -------------- What is the difference between the two? Why 'none' is being printed as an output in first one?
5 Réponses
+ 2
Try it like this:
def mf():
return 'rt\n'*2
print(mf())
it is usually better in functional programming to avoid side effects in a function. If the function's purpose is to figure out a value, using any parameters, then that value should be returned, and you can do the printing from the main program where the function is called.
If the function's purpose is to print something then maybe it does not need to return anything and it does not make sense to 'print' this nothing again in the main program.
This distincrion is much clearer in purely OOP languages where you must declare the return type as 'void' if your function doesn't return any value. Python is much more forgiving with this, and that can confuse beginners.
+ 1
Thanks Tibor Santa
0
because the first one try to print the value returned by the print(). and i think it print none, because the print function is not return anything
0
Please elaborate... as I have worked on similar type of code where a function was created to get price of some item from a website (let say that fn. be get_price() ) and when I used print(get_price()) (depending on whether the user wants to see the price or not) then nothing like this(printing 'none' at end) happened.....
0
https://docs.python.org/3/library/functions.html#print
you can see, the print function also accept None as the parameter. and also it doenst return anything, that means no value. and None is actually an object that usually used to represent the absence of a value. ( https://docs.python.org/3.2/library/constants.html )