Reputation: 44352
I see some examples where return
is the last statement in a function that doesn't return anything. Is this needed in Python 3.x?
def myfunc():
result = 1 + 1
return
Upvotes: 0
Views: 55
Reputation: 19174
As others said, "No". For a function that mutates the input or causes a side-effect, return
or return None
should be omitted, unless needed for early exit, in which case I would use return
. However, I might use return None
here:
def pos(x):
if x > 0:
return x
else:
return None
This could be condensed to this:
def pos(x):
return x if x > 0 else None
Upvotes: 0
Reputation: 23233
Return statements are not mandatory, if function exits without any return statement, None
is returned.
Proof:
Quoting official docs, namely Calls and The return statement:
About return:
return leaves the current function call with the expression list (or None) as return value.
About calls:
A call always returns some value, possibly
None
, unless it raises an exception. How this value is computed depends on the type of the callable object.If it is a user-defined function:
The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section Function definitions. When the code block executes a return statement, this specifies the return value of the function call.
As we can conclude from docs - all functions implicitly returns None
, unless explicit return
statement is executed.
Upvotes: 1
Reputation: 1298
If the last statement in a function is return
, then it return
s a value. If there is no return
statement, it does not return
anything.
Upvotes: 0