Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:
>>> def dbl_a(p): return p*2 >>> def dbl_b(p): return(p*2) >>> def dbl_c(p): return (p*2)
If we run them we get:
>>> dbl_a(42) 84 >>> dbl_b(42) 84 >>> dbl_c(42) 84
The three functions provide the same result (value and type) and they seem to be equivalent.
But which of them has the more correct return
statement?
Is there any side-effect in any of those definitions?
The same questions apply to the following situation with multiple values returned:
>>> def dbl_triple_a(p): return p*2, p*3 >>> def dbl_triple_b(p): return(p*2, p*3) >>> def dbl_triple_c(p): return (p*2, p*3) >>> dbl_triple_a(42) (84, 126) >>> dbl_triple_b(42) (84, 126) >>> dbl_triple_c(42) (84, 126)
In this case every function returns a tuple, but my questions still remain the same.
Even then parentheses are not needed. return x + y; Programmers do make it return (x + y); to make it more readable. So, putting parentheses is a matter of opinion and practice. With respect to java, parentheses does not make any difference.
If a return statement is used, it must not contain an expression.
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
return value
is the "correct" way - return is a language construct, not a function.
If you want to return a tuple, use return your, values, here
There's no need for any parenthesis (tuples are created by the ,
"operator", not the ()
)
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