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.
Almost all the operators have left-to-right associativity. For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first. Note: Exponent operator ** has right-to-left associativity in Python.
All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Thus "==" and "<" have the same priority, why would the first expression in the following evaluate to True , different from the 2nd expression?
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.
A comparison operator in python, also called python relational operator, compares the values of two operands and returns True or False based on whether the condition is met.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With