"If (a == b):" or "if a == b:" in Python, which one is correct?

1

I have already 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?

    
asked by anonymous 04.03.2018 / 23:14

1 answer

4

As well as commented, one of the principles of the Python language is the readability of the code.

  

Readability counts.

In this way, reading if a is much closer to natural than if (a) . Without the separating white space is even worse, because it resembles the function call syntax, which can generate a temporary, even if very short, confusion when reading the code. In fact, the three forms would work the same way, so the final answer will even be the one you prefer. Particularly I would take the first one and would use the parentheses only when necessary, as, for example, to define the order of evaluation before the precedence of the operators.

Let's say you need to split a a variable by twice the b variable. If you only do a / 2*b , you would not get the desired result because what would be calculated would be a/2 , result multiplied by b . This is because of the precedence of the operators, which in this case are the same and therefore are evaluated from left to right. To get the desired result, you will need to control the order of evaluation using the parentheses: a / (2*b) .

    
05.03.2018 / 00:50