Priority of the Logical Operators Not, And, or in Python

Python `or`, `and` operator precedence example

You are confusing operator precedence and evaluation order.

The expression r = x or y and z is not evaluated as tmp = y and z; r = x or tmp, but just as r = x or (y and z). This expression is evaluated from left to right, and if the result of the or is already decided, then (y and z) will not be evaluated at all.

Note that it would be different if or and and were functions; in this case, the parameters of the functions would be evaluated before the function itself is called. Hence, operator.or_(yay(), operator.and_(nay(), nope())) prints yay, nay and nope i.e. it prints all three, but still in order from left to right.

You can generalize this to other operators, too. The following two expressions will yield different results due to the different operator precedence (both implicit and explicit by using (...)), but the functions are called from left to right both times.

>>> def f(x): print(x); return x
>>> f(1) + f(2) * f(3) / f(4) ** f(5) - f(6) # 1 2 3 4 5 6 -> -4.99
>>> (f(1) + f(2)) * (((f(3) / f(4)) ** f(5)) - f(6)) # 1 2 3 4 5 6 -> -17.29

As pointed out in comments, while the terms in between operations are evaluated from left to right, the actual operations are evaluated according to their precedence.

class F:
def __init__(self,x): self.x = x
def __add__(self, other): print(f"add({self},{other})"); return F(self.x+other.x)
def __mul__(self, other): print(f"mul({self},{other})"); return F(self.x*other.x)
def __pow__(self, other): print(f"pow({self},{other})"); return F(self.x**other.x)
def __repr__(self): return str(self.x)
def f(x): print(x); return F(x)

This way, the expression f(1) + f(2) ** f(3) * f(4) is evaluated as 1, 2, 3, pow(2,3), 4, mul(8,4), add(1,32), i.e. terms are evaluated left-to-right (and pushed on a stack) and expressions are evaluated as soon as their parameters are evaluated.

computation of multiple logical operators or ,and in one statement

It follows the precedence order as defined in operator precedence.

In short, NOT > AND > OR.

Your code translates to:

(6 and 0) or (5==9 and 4 and '7') or (0 and 8)
(4) or (8 and 56==0) or (5 and 0) or (5 and 'hoe') or (0 and 'f')


Related Topics



Leave a reply



Submit