Python入门示例系列30 Python运算符优先级和结合性

 

 

表 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/

 

posted @ 2022-02-11 17:45  emanlee  阅读(246)  评论(0编辑  收藏  举报