Reputation: 11
a = 2
b = 1
if a == 2 | b == 1:
print(a, b)
this won't print the values of a & b
a = 2
b = 1
if ((a == 2) | (b == 1)):
print(a, b)
this will print the values
why so?
Upvotes: 1
Views: 394
Reputation: 2477
|
is the bitwise OR
operator and it has higher precedence than ==
. So if brackets are not used, 2 | b
is executed at the start in the first program.
(2 | b) -> (2 | 1) -> (3)
Then when a==3
is checked, it returns False, since a=2
I think you could use the or
instead of |
here if you want to to execute the statement by checking values of a and b.
Upvotes: 1
Reputation: 57033
Operator ==
in Python has a lower precedence than the operator |
. So:
a == 2 | b == 1
is equivalent to:
a == (2 | b) == 1
which, in turn, is equivalent to:
(a == (2 | b)) and ((2 | b) == 1)
Given that a==2
, at least one of the subexpressions must be false, regardless of b
.
Upvotes: 5