Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a return statement have parentheses?

Tags:

python

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.

like image 673
Chaos Manor Avatar asked Feb 12 '11 14:02

Chaos Manor


People also ask

Does return need parentheses Java?

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.

Can a return statement have an expression?

If a return statement is used, it must not contain an expression.

Can a return statement be used without 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.

When should you use a return statement?

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.


1 Answers

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 ())

like image 80
ThiefMaster Avatar answered Sep 29 '22 14:09

ThiefMaster