Home > Software design >  bitwise AND ini python for comparison
bitwise AND ini python for comparison

Time:11-11

>>> i=5
>>> i>4 & i<5
True
>>> i>4 and i<5
False

I am not able to understand how bitwise AND is used here? The second statement can be understood as 5 is not less than 5, hence it returns false. Can someone throw some light on the first statement?

CodePudding user response:

I have done a bit of experimentation in the python shell and i believe that i know what is going on here. I ran:

>>> 5>4 & 5<5
True
>>> 1 & 0
0
>>> True & False
False
>>> (5>4) & (5<5)
False
>>> (5>4 & 5)<5
True

So I believe what is happening is it is performing (5>4 & 5)<5 instead of (5>4) & (5<5)

CodePudding user response:

& applies before > which applies before and

  • a > b and a > c, it's parsed as (a > b) and (a > c)

  • a > b & a > c, it's parsed as a > (b & a) > c

  • Related