0
Where Boolean Condition Start? is left?
hour = 9 day = 23 hour > 12 and day <= 15 or hour < 10 True
3 Answers
+ 3
Hi, RHAMAD NURSANI SIDIK !
Itâs better to use parentheses when constructing logical expressions:
A and B or C works, but
(A and B) or C improves readability and reduces the risk of misunderstandings.
Python stops evaluating the expression from left to right as soon as it becomes true; otherwise, it continues evaluating.
+ 2
Yes it's like in math. From left to right.
9 > 12 and 23 <= 15 or 9 < 10
false and false or true
false or true
true
+ 1
RHAMAD NURSANI SIDIK ,
It's only left to right if the operators have the same precedence.
Comparison operators all have the same precedence as each other but higher precedence than the logical operators, and each of the logical operators (not and or) has its own precedence. It's complex but sensible, and you get used to it after a while.
Best thing to do -- keep the precedence table handy and use gratuitous parentheses when in doubt.
https://docs.python.org/3/reference/expressions.html?highlight=precedence#operator-precedence
[Edit] By the way, in that table, the "not" operator is written as "not x" because they wanted to show that it takes only a single operator, which is a misleading way to do it in my opinion, because it makes it confusable with the actual two-word operators, "not in" and "is not", but the way to type the "not" operator in code is still just "not".