在 Python 中連結比較運算子


有時候我們需要在一個語句中使用多個條件判斷。此類檢查有一些基本語法,例如 x < y < z,或者 if x < y and x < z 之類。

像其他語言一樣,Python 中有一些基本比較運算子。這些比較運算子為 <、<=、>、>=、==、!=、is、is not、in、not in。

這些運算子的優先順序相同,且優先順序低於算術、位操作和移位運算子。

這些運算子可以任意排列。它們將連結使用。所以,例如,如果表示式為 x < y < z,則它類似於 x < y and y < z。由此例中,我們可以看到如果運算元為 p1、p2、...、pn,而運算子為 OP1、OP2、...、OPn-1,則其將與 p1 OP1 p2 和 p2 OP2 p3 相同,分別為 pn-1 OPn-1pn

因此有關於比較運算子連結特性的示例。

示例程式碼

即時演示

a = 10
b = 20
c = 5
# c < a < b is same as c <a and a < b
print(c < a)
print(a < b)
print(c < a < b)
# b is not in between 40 and 60
print(40 <= b <= 60)
# a is 10, which is greater than c
print(a == 10 > c)

輸出

True
True
True
False
True

示例程式碼

即時演示

u = 5
v = 10
w = 15
x = 0
y = 7
z = 15
# The w is same as z but not same as v, v is greater than x, which is less than y
print(z is w is not v > x < y)
# Check whether w and z are same and x < z > y or not
print(x < w == z > y)

輸出

True
True

更新於: 2019 年 7 月 30 日

769 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告