表 1 Python 运算符优先级和结合性一览表
运算符说明Python运算符优先级结合性优先级顺序
小括号
( )
19
无
高
︿
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
低
索引运算符
x[i] 或 x[i1: i2 [:i3]]
18
左
属性访问
x.attribute
17
左
乘方
**
16
右
按位取反
~
15
右
符号运算符
+(正号)、-(负号)
14
右
乘除
*、/、//、%
13
左
加减
+、-
12
左
位移
>>、<<
11
左
按位与
&
10
右
按位异或
^
9
左
按位或
|
8
左
比较运算符
==、!=、>、>=、<、<=
7
左
is 运算符
is、is not
6
左
in 运算符
in、not in
5
左
逻辑非
not
4
右
逻辑与
and
3
左
逻辑或
or
2
左
逗号运算符
exp1, exp2
1
左
示例:
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # (30) * (15/5)
print("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)
输出结果:
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
REF
https://www.tutorialspoint.com/python/operators_precedence_example.htm#:~:text=Python%20Operators%20Precedence%20Example%20%20%20%20Operator,Addition%20and%20subtraction%20%209%20more%20rows%20
http://c.biancheng.net/view/2190.html
https://pythongeeks.org/python-operator-precedence/
发表评论