Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (1 == 2 != 3) evaluate to False in Python?

Why does (1 == 2 != 3) evaluate to False in Python, while both ((1 == 2) != 3) and (1 == (2 != 3)) evaluate to True?

What operator precedence is used here?

like image 252
Mo Xu Avatar asked Dec 20 '17 06:12

Mo Xu


People also ask

Why is true and false false in Python?

In Python, the two Boolean values are True and False (the capitalization must be exactly as shown), and the Python type is bool. In the first statement, the two operands evaluate to equal values, so the expression evaluates to True; in the second statement, 5 is not equal to 6, so we get False.

Does == mean true in Python?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.

What does != Mean in Python 3?

In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal.


2 Answers

A chained expression like A op B op C where op are comparison operators is in contrast to C evaluated as (https://docs.python.org/2.3/ref/comparisons.html):

A op B and B op C

Thus, your example is evaluated as

1 == 2 and 2 != 3

which results to False.

like image 61
clemens Avatar answered Oct 09 '22 12:10

clemens


This is due to the operators chaining phenomenon. The Pydoc explains it as :

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).

And if you look at the precedence of the == and != operators, you will notice that they have the same precedence and hence applicable to the chaining phenomenon.

So basically what happens :

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False
like image 25
Kaushik NP Avatar answered Oct 09 '22 12:10

Kaushik NP