Is `a<b<c` valid python?

蹲街弑〆低调 提交于 2019-12-17 18:51:55

问题


I was curious to see if I could use this a<b<c as a conditional without using the standard a<b and b<c. So I tried it out and my test results passed.

a = 1
b = 2
c = 3

assert(a<b<c) # In bounds test
assert(not(b<a<c)) # Out of bounds test
assert(not(a<c<b)) # Out of bounds test

Just for good measure I tried more numbers, this time in the negative region. Where a, b, c = -10, -9, -8. The test passed once again. Even the test suit at a higher range works a, b, c = 10, 11, 12. Or even a, b, c = 10, 20, 5.

And the same experiment done in C++. This was my mentality going into it:

#include <iostream>

using namespace std;

int main()
{
    int a,b,c;
    a=10;
    b=20;
    c=5;
    cout << ((a<b<c)?"True":"False") << endl; // Provides True (wrong)
    cout << ((a<b && b<c)?"True":"False") << endl; // Provides False (proper answer)
    return 0;
}

I originally though that this implementation would be invalid since in every other language I have come across would evaluate a boolean before it would reach c. With those languages, a<b would evaluate to a boolean and continuing the evaluation, b<c, would be invalid since it would attempt to evaluate a boolean against a number (most likely throwing a compile time error or falsifying the intended comparison). This is a little unsettling to me for some reason. I guess I just need to be reassured that this is part of the syntax. It would also be helpful to provide a reference to where this feature is provided in the Python documentation so I can see to what extent they provide features like this.


回答1:


This is documented here.

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.

And, as an example,

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).




回答2:


Python chains relational operators "naturally". Note that Python's relational operators include in and is (and their negatives), which can lead to some surprising results when mixing them with the symbolic relational operators.




回答3:


a < b < c
it executes as follows

(a < b) < c
(false) < c => (0) <c
true.....
this happens for you



来源:https://stackoverflow.com/questions/18755059/is-abc-valid-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!