Home > other >  Do parenthesis force the content within to be executed first?
Do parenthesis force the content within to be executed first?

Time:07-14

I have multiple conditions in an if statement:

if x > 0.01 and x < 0.015 and y != 0 and (var_1 == var_2 == 0):
    #do...

Now from the reading i did, the parentheses will be executed first, am i correct in saying that? Secondly, are the parentheses in this example redundent if it does not matter that its checked first?

CodePudding user response:

The chained comparisons in parentheses are equivalent to

(var_1 == var_2 and var_2 == 0)

So your whole expression is equivalent to

if x > 0.01 and x < 0.015 and y != 0 and (var_1 == var_2 and var_2 == 0):

See documentation

The parentheses are redundant and the terms will still be evaluated left to right with short-circuiting.

  • Related