在 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
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例代码
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
广告