Rahul Kumar
Rahul Kumar

Reputation: 49

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

Upvotes: 0

Views: 1686

Answers (2)

Mufeed
Mufeed

Reputation: 3228

Answer to your first question. Python & operator will be executed first than == operator(due to higher precedence)

Answer to your second question.

if a==b & a==20:

When you executed this expression internally this is what happened.

if a==(b&a)==20:

The expression (b&a) will give you the answer 20. So the expression is like this now.

if a==(20)==20:  # which is nothing but if a==20 and 20==20:

Since a = 20,the expression becomes true and you get the if part executed. But when you interchanged a and be this is what actually happened.

if b==(a&a)==20:

a&a again will give you 20. So the expression becomes

if b==(20)==20:    # if b==20 and 20==20:

Now b is not 20,its 30. So expression becomes False and else part gets executed.

Upvotes: 4

himabindu
himabindu

Reputation: 336

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"

Upvotes: 2

Related Questions