Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `True is False == False`, False in Python? [duplicate]

Why is it that these statements work as expected when brackets are used:

>>> (True is False) == False True  >>> True is (False == False) True 

But it returns False when there are no brackets?

>>> True is False == False False 
like image 801
Samuel O'Malley Avatar asked Jul 11 '15 07:07

Samuel O'Malley


People also ask

Is false == false true?

False == (False or True) In this expression python would first solve the comparison operator in bracket. => (False or True) is said to be True. Because the 'OR' operator search for the first truthy value, and if found it returns the value else 'False'. Now we have: =>False == True is False.

Does 1 == true evaluate true or false 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.

Why does Python capitalize true and false?

True and False in Python are capitialised because they are constants and it is common practice to capitialise constants in Python. Other languages with similar naming practices tend not to follow it for whatever reason. The language is also case sensitive meaning true and True are different according to Python.


1 Answers

Based on python documentation about operator precedence :

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

So actually you have a chained statement like following :

>>> (True is False) and (False==False) False 

You can assume that the central object will be shared between 2 operations and other objects (False in this case).

And note that its also true for all Comparisons, including membership tests and identity tests operations which are following operands :

in, not in, is, is not, <, <=, >, >=, !=, == 

Example :

>>> 1 in [1,2] == True False 
like image 160
Mazdak Avatar answered Oct 03 '22 02:10

Mazdak