Chain comparison python

Reference  https://www.cnblogs.com/shanghongyun/p/10519579.html

Why Python "2 == 2> 1" to True
in Python, you might find this a strange phenomenon:

2 == 2 >>>> 1
True
>>> (2 == 2)> 1
False
>>> 2 == (2> 1)
False
Why is there results 2 == 2> 1 is True? If this is a priority issue operators, then why did the two formulas are False?

In fact, this involves the comparison of Python chain (ChainedComparisons). In other languages, there is a variable x, if x is greater than 1 is determined to be less than 5, you may need to write code:

if (x> 1 and x < 5)
but in Python, the code can be written:

. 1 IF <X <. 5
the Python correctly handles the comparison logic chain. Back to the beginning of the problem, and == equal sign <less than symbol, the essence no different. So in fact 2 2 ==> 1 is a chain of formula contrast, which corresponds to 2 == 2and2> 1. At this point, this formula is equivalent to TrueandTrue. So the result returned is True.

Note: True is equivalent to 1, False is equivalent to 0

Original from: https: //cloud.tencent.com/developer/article/138694

Guess you like

Origin www.cnblogs.com/weiwuxian/p/11368936.html
Recommended