python – Conditional expression with or and and predicates does not work correctly

Question:

a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == c or a == c + 1 or a == c - 1 and b == d or b == d + 1 or b == d - 1:
    print("YES")
else:
    print("NO")

I am trying to solve the problem for the rook move. 4 values ​​are entered and you need to find out if the rook can go like this. Described all the steps of the rook, but when you enter 4322, YES is displayed.

Why is the condition not triggered?

Answer:

It's all about the priority of operations.

In order to understand how this construction is interpreted, I propose to simplify it by replacing each comparison with the result – False / True .

Get it:

False or False or False and False or True or False

this construction is interpreted from left to right and the first four predicates:

False or False or False and False

can be simplified to the only False – it turns out:

False or True or False

the result is True


NOTE: for the future – if both or and and predicates are present in the comparison string, then set the precedence explicitly using parentheses:

print((False or False or False) and (False or True or False))
# False
Scroll to Top