I just learned (am learning) how function parameters work in Python, and I started experimenting with it for no apparent reason, when this:
def jiskya(x, y): if x > y: print(y) else: print(x) print(jiskya(2, 3))
gave the ouput:
>>> 2 None
Where did the None
come from? And what is it?
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.
If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').
As other have answered, the result is exactly the same, None is returned in all cases. The difference is stylistic, but please note that PEP8 requires the use to be consistent: Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should.
It's the return value of the function, which you print out. If there is no return statement (or just a return
without an argument), an implicit return None
is added to the end of a function.
You probably want to return the values in the function instead of printing them:
def jiskya(x, y): if x > y: return y else: return x print(jiskya(2, 3))
Ok, to start off when you do this:
print(jiskya(2, 3))
You getting something pretty much equivalent to this:
print(print(2))
So, what is going on? The print(2)
is printing out 2, and returns None
which is printed by the outer call. Straightforward enough.
Now look at this:
def hello(): return 2
If you do:
print(hello())
You get 2 because if you print out a function you get whatever the return
value is. (The return
value is denoted by the return someVariable
.
Now even though print
doesn't have parenthesis like most functions, it is a function just a little special in that respect. What does print return? Nothing. So when you print print someVariable
, you will get None
as the second part because the return value of print is None
.
So as others have stated:
def jiskya(x, y): if x > y: print(y) else: print(x)
Should be re-written:
def jiskya(x, y): if x > y: return y else: return x
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