Python 运算符的优先级
值、变量、运算符和函数调用的组合被称为表达式。Python 解释器可以计算一个有效的表达式。
例如
>>> 5 - 7
-2
这里 5 - 7
就是一个表达式。一个表达式中可以有多个运算符。
为了计算这类表达式,Python 中有一套优先级规则。它指导着这些运算的执行顺序。
例如,乘法的优先级高于减法。
# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2
但是我们可以使用括号 ()
来改变这个顺序,因为括号的优先级比乘法更高。
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12
Python 中的运算符优先级在下表中列出。它是按降序排列的(上面的组比下面的组有更高的优先级)。
运算符 | 含义 |
---|---|
() |
括号 |
** |
幂 |
+x , -x , ~x |
一元正、一元负、按位非 |
* , / , // , % |
乘法、除法、整除、取模 |
+ , - |
加法、减法 |
<< , >> |
按位移位运算符 |
& |
按位与 |
^ |
按位异或 |
| |
按位或 |
== , != , > , >= , < , <= , is , is not , in , not in |
比较运算符、身份运算符、成员资格运算符 |
not |
逻辑非 |
and |
逻辑与 |
or |
逻辑或 |
我们来看一些例子
假设我们正在构建一个 if...else 代码块,当 lunch 是 fruit 或 sandwich,并且只有当 money 大于或等于 2 时,才运行 if
块。
# Precedence of or & and
meal = "fruit"
money = 0
if meal == "fruit" or meal == "sandwich" and money >= 2:
print("Lunch being delivered")
else:
print("Can't deliver lunch")
输出
Lunch being delivered
即使 money 是 0,这个程序也会运行 if
块。它没有给出我们期望的输出,因为 and
的优先级高于 or
。
我们可以通过以下方式使用括号 ()
来得到期望的输出
# Precedence of or & and
meal = "fruit"
money = 0
if (meal == "fruit" or meal == "sandwich") and money >= 2:
print("Lunch being delivered")
else:
print("Can't deliver lunch")
输出
Can't deliver lunch
Python 运算符的结合性
我们可以在上表中看到,多个运算符存在于同一个组中。这些运算符具有相同的优先级。
当两个运算符具有相同的优先级时,结合性有助于确定运算的顺序。
结合性是指当一个表达式中有多个相同优先级的运算符时,表达式的计算顺序。几乎所有的运算符都具有从左到右的结合性。
例如,乘法和整除具有相同的优先级。因此,如果它们都出现在一个表达式中,左边的会先被计算。
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
输出
3 0
注意:幂运算符 **
在 Python 中具有从右到左的结合性。
# Shows the right-left associativity of **
# Output: 512, Since 2**(3**2) = 2**9
print(2 ** 3 ** 2)
# If 2 needs to be exponated fisrt, need to use ()
# Output: 64
print((2 ** 3) ** 2)
我们可以看到 2 ** 3 ** 2
等价于 2 ** (3 ** 2)
。
非结合性运算符
一些运算符,如赋值运算符和比较运算符,在 Python 中没有结合性。对于这类运算符的序列有单独的规则,不能表示为结合性。
例如,x < y < z
既不意味着 (x < y) < z
也不意味着 x < (y < z)
。x < y < z
等价于 x < y and y < z
,并且是从左到右计算的。
此外,虽然像 x = y = z = 1
这样的链式赋值是完全有效的,但 x = y = z+= 2
会导致错误。
# Initialize x, y, z
x = y = z = 1
# Expression is invalid
# (Non-associative operators)
# SyntaxError: invalid syntax
x = y = z+= 2
输出
File "<string>", line 8 x = y = z+= 2 ^ SyntaxError: invalid syntax