1. 程式人生 > >從1<2<3的語法糖說起

從1<2<3的語法糖說起

als 因此 語言 意思 and 運算 right 意義 logs

python有一個很有意思的語法糖你可以直接寫1<2<3。

這復合我們通常意義上的數學不等式,但對學過C等語言其實是有疑惑的。

我們知道不等式返回的其實是個Bool值,在C中是1,0因此C中下面情況是正確的

0<0<1

因此我們看下面這個情況

True == True == False
#False
False == False == True
#False

從通常意義來說==號從右往左結合,無論如何值都應該是True,但是結果確是False

這就是源於python的一個語法糖,對於運算優先級的規定。

所有比較類型的運算符擁有同樣的優先級,會從左至右鏈接起來共同作為一個比較段( all have the same precedence and have a left-to-right chaining

feature as described in the Comparisons section)。

in, not in, is, is not, <, <=, >, >=, !=, ==

比如一個典型的True == True == False它實質是如下的邏輯關系

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

同樣1<2<3實質是

1<2 and 1<3

從1<2<3的語法糖說起