Search code examples
pythonconditional-operatorcomparison-operators

Comparison operators give different values for | & compared to and or - Python


I'm confused by comparison operators. For example,

 10 or 20 == 20
 # output, expected True
 10

  10 | 20 == 20
 (10 | 20) == 20
 (10 or 20) == 20

All 3 lines of code give 'False', yet I was expecting 'True'.

 10 or 20 == 20
 # output gives 10, but was expecting True
 10

Another example:

 10 and 20 > 2
 # output is as expected
 True

 (10 and 20) > 2
 True

 (10 & 20) > 2
 # output gives False, but was expecting True
 False

Lastly, if I do:

 10 or 20 > 100
 #output is 10. No idea why
 10
 3 or 8 < 200
 3

Can anyone help clear up this confusion? Much appreciated for taking the time to read my perplexion! I'm using Python 3.6


Solution

  • It is similar to True or false case :

    >>> 20 or 10
    20
    >>>(20 or 10) == 10 
    False
    >>>(20 or 10) == 20
    True
    

    This is because It takes the first value as true and next as false and when you pass true or false you get true similarly you get 20 which actually represents true here. Hope this helps.