Reputation: 1833
So I was looking at some code online and I came across a line (at line 286):
if depth > 0 and best <= -MATE_VALUE is None and nullscore > -MATE_VALUE:
The part I had trouble understanding was the best <= -MATE_VALUE is None
.
So I fired up the interpreter to see how a statement such as value1 > value2 is value3
work.
So I tried
>>> 5 > 2 is True
False
>>> (5 > 2) is True
True
>>> 5 > (2 is True)
True
My Question
Why is 5 > 2 is True
not True
? And how do these things generally work?
Thanks.
Upvotes: 9
Views: 365
Reputation: 3857
First, 5 > 2 is True
is equivalent to (5 > 2) and (2 is True)
because of operator chaining in python (section 5.9 here).
It's clear that 5 > 2
evaluates to True. However, 2 is True
will evaluate to False
because it is not implicitly converted to bool
. If you force the conversion, you will find that bool(2) is True
yields True
. Other statements such as the if
-statement will do this conversion for you, so if 2:
will work.
Second, there is an important difference between the is
operator and the ==
operator (taken from here):
Use
is
when you want to check against an object's identity (e.g. checking to seeif var is None
). Use==
when you want to check equality (e.g. Is var equal to 3?).
>> [1,2] is [1,2]
False
>> [1,2] == [1,2]
True
While this does not have an immediate impact on this example, you should keep it in mind for the future.
Upvotes: 3
Reputation: 3650
You're seeing python's operator chaining working
5 > 2 is True
Is equivalent to
5>2 and 2 is True
You can see this in that
>>> 5>2 is 2
Returns True
.
Upvotes: 8