print(2==2==True)
gives the result : False
so my query is why it doesn't give answer as True?
Where as :
print(2==2 and True)
gives the result: True
can anyone give a satisfactory answer?
print(2==2==True)
gives the result : False
so my query is why it doesn't give answer as True?
Where as :
print(2==2 and True)
gives the result: True
can anyone give a satisfactory answer?
When you do:
print(a == b == c)
You are checking if the values of a, b, and c are the same. Since 2 is NOT equal to True, the statement is false, and the output of
print(2 == 2 == True)
will be False.
However, when you do:
print(2 == 2 and True)
You are checking that if BOTH 2 == 2 and True have the boolean values of True, then you will print out True, and otherwise False. Since 2 does equal 2, the expression 2 == 2 is True. Thus, True and True is True, so the output will be True.
Let me know if you have sny further questions or clarifications!
From python docs:
Comparisons:
Comparisons can be chained arbitrarily, e.g.,
x < y <= zis equivalent tox < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all whenx < yis found to be false).Formally, if
a,b,c, …,y,zare expressions andop1,op2, …,opNare comparison operators, thena op1 b op2 c ... y opN zis equivalent toa op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
In your first example,
print(2 == 2 == True) # This is in the form `a op b op c`
is equivalent to 2 == 2 and 2 == True. which is True and False.
In your second example, there would be no chaining since and is not comparison operator.
print(2 == 2 and True)
is equivalent to 2 == 2 and True, which is True and True.
If you want to force evaluation of an expression first then put the expression inside ().
print((2 == 2) == True)
print((2 == 2) and True)
In the first Case 2==2==True You are testing three conditions which is like.
2==2 => True2==True => FalseTrue==2 => False (Don't need check because if first 2 fulfills then this one is also trueand in Second Case `2==2 and True' You are testing two conditions which is like.
2==2 => True True and True => TrueThe == operator compares the value or equality of objects. print(2==2==True) means you are comparing three objects together. 2 equals 2 as both values are equal but 2 and 2 is value whereas True is equality so overall value becomes false.
print(2==2 and True) means you are comparing equality of 2==2 and True. 2 equals 2 as both values are equal and equality is True. True is equality so True and True equality becomes true.