Home > Enterprise >  I have a confusion with regard to print(10==10==True) and print(10==10 and True) in Python
I have a confusion with regard to print(10==10==True) and print(10==10 and True) in Python

Time:06-27

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?

CodePudding user response:

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!

CodePudding user response:

From python docs:

Comparisons:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a 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)

CodePudding user response:

In the first Case 2==2==True You are testing three conditions which is like.

  1. 2==2 => True
  2. 2==True => False
  3. True==2 => False (Don't need check because if first 2 fulfills then this one is also true

and in Second Case `2==2 and True' You are testing two conditions which is like.

  1. 2==2 => True
  2. True and True => True

CodePudding user response:

The == 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.

  • Related