Reputation: 81
I try to understand the difference between the logical operand and
and the bitwise operand &
.
So I wrote two statements and get unexpected outcomes.
I understand the first one and expect the second one would give me the same outcome as the first one.
The first one I get the False which is what I want. But the second one I get True which makes me confused.
Since 3%3 == 0
return True
,and 3%5 == 0
return False
. And True & False
gives me False
. Why, when I put them together, do I get the True
? Can someone explain why the second one gives me the True
instead of False
?
3 % 3 == 0 and 3 % 5 == 0
3 % 3 == 0 & 3 % 5 ==0
3 % 3 == 0
3 % 5 == 0
True & False
Upvotes: 0
Views: 122
Reputation: 23174
Operators priority is probably the source of confusion here.
&
has higher precedence than ==
, whereas and
has a lower one.
This means the second case is the same as 3 % 3 == (0 & 3 % 5) == 0
If you add more parenthesis to show the order, these are equivalent:
(3 % 3) == (0 & (3 % 5)) == 0
0 == (0 & 3) == 0
0 == 0 == 0 // True
Note: the last chain of ==
is interpreted as the equality test between all three operands, and is obviously true here. Thanks @kaya for clarification comment.
Upvotes: 5
Reputation:
Remember than and means that both the expressions must be correct
3 % 3 == 0 and 3 % 5 == 0
print( 3 % 3 )
0
print( 3 % 5)
3
0
So if we simplify it, it becomes
3 % 3 == 0 and 3 % 5 == 0
True and False:
Both conditions are not true, hence the answer is false.
3 % 3 == 0 & 3 % 5 == 0
The answer comes when we look at operator precendence
&
has a higher precedence than ==
Hence, the statement is basically
3 % 3 == (0 & 3) % 5 == 0
Upvotes: 2