1
I’ve seen two ways to express conditional in python, using or not ().
With ():
if(a):
print('x')
Without ():
if a:
print('x')
Which of the two ways would be the most correct to use?
1
I’ve seen two ways to express conditional in python, using or not ().
With ():
if(a):
print('x')
Without ():
if a:
print('x')
Which of the two ways would be the most correct to use?
4
As commented, one of the principles of the Python language is the readability of the code.
Thus, read if a
is much closer to the natural than if (a)
. Without the separating whitespace it is even worse, because it resembles the function call syntax, which can cause temporary confusion, even if very short, when reading the code. In fact, the three ways would work the same way, so the final answer will be the one you prefer. Particularly I would stay with the first and use the parentheses only when necessary, as, for example, to define the order of evaluation before the precepts of the operators.
Say you need to split a variable a
for twice the variable b
. If you just a / 2*b
, you would not get the desired result as what would be calculated would a/2
, result multiplied by b
. This occurs because of the precedence of the operators who, in this case, are the same and are therefore evaluated from left to right. To get the desired result, you will need to control the evaluation order with the use of parentheses: a / (2*b)
.
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.
I think it’s still going to be a condition like this:
if bar > 2 * (1 + 2)
it seems easier to read than to read:if (bar > 2 * (1 + 2))
but there’s taste.– gato
At pep8 is done as follows if foo == 'blah':
– user73316