Function returns None without return statement
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
Where did the 'None' come from?
The function.
And what is it?
It's what the function returned.
In Python, every function returns something. It could "be multiple things" using a tuple, or it could "be nothing" using None
, but it must return something. This is how we deal with the fact that there is no way to specify a return type (which would make no sense since you don't specify types for anything else). When interpreted as a string for printing, None
is replaced with the string "None".
None
is a special object that is supposed to represent the absence of any real thing. Its type is NoneType
(it is an instance of that class). Whenever you don't explicitly return anything, you implicitly return None.
You wrote the function to print one of the two values x
or y
, but not to return anything. So None
was returned. Then you asked Python to print the result of calling the function. So it called the function (printing one of the values), then printed the return value, which was None
, as the text "None".