A question about identity and boolean in Python3

Viewed 93

I have a question about identity in python, i'm a beginner in python and i have read some courses on "is" keyword and "is not". And i don't understand why the operation "False is not True is not True is not False is not True" equals False in python ? For me this operation have to return True.

3 Answers

Python chains comparisons:

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.

Your expression is:

False is not True is not True is not False is not True

Which becomes:

(False is not True) and (True is not True) and (True is not False) and (False is not True)

Which is equivalent to:

(True) and (False) and (True) and (True)

Which is False.

is relates to identity.

When you ask if x is y, you're really asking are x and y the same object? (Note that this is a different question than do x and y have the same value?)

Likewise when you ask if x is not y, you're really asking are x and y different objects?

Specifically in regards to True and False, Python treats those as singletons, which means that there is only ever one False object in an entire program. Anytime you assign somnething to False, that is a reference to the single False object, and so all False objects have the same identity.

You are dealing with logic. It helps to think about True = 1 and False = 0.

Think about it this way. 0 is not 1, that will return True because the number 0 is not the number 1 and is a true statment. Same concept with True and False

0 is not 1
#this will return False
False is not True
#the computer reads this in the exact same manner.
Related