pythonpython-3.xif-statementlogical-operators

In python 3 logical operator giving me an opposite result


I was working in Python 3, I created one If-else statement with the logical operator "&". the result that got was inverse of what actually should have appeared. As: a=20 b=30

if a==b & a==20:
    print("a is equal to b")
else:
    print ("a is not equal to b")

enter image description here

This condition should have printed out the else condition since the first statement "a==b" is a false statement and the second statement "a==20" is true. Mathematical logic says when a statement in "&" condition is false result would be false. The strange thing happened when I replaced the condition "a==b" with "b==a", the result was correct.

enter image description here


Solution

  • In Python '&' has higher precedence than '==' so We are getting the wrong result Try this:

    if (a==b) & (a==20):
        print "a is equal to b"
    else:
        print "a is not equal to b"