Heyiki’s Blog

下表列出了从最高优先级到最低优先级的所有运算符,如下所示

序号运算符描述
1    |    `**`   |    指数(次幂)运算    
2    |    `~` `+` `-`    |    补码,一元加减(最后两个的方法名称是`[email protected]`和`[email protected]`)    
3    |    `*` `/` `%` `//`    |    乘法,除法,模数和地板除    
4    |    `+` `-`    |    加法减法    
5    |    `>>` `<<`    |    向右和向左位移    
6    |    `&`    |    按位与    
7    |    `^`  &#124;   |    按位异或和常规的“`OR`”    
8    |    `<=` `<` `>` `>=`    |    比较运算符    
9    |    `<>` `==` `!=`   |    等于运算符    
10    |    `=` `%=` `/=` `//=` `-=` `+=` `*=` `**=`    |    赋值运算符    
11    |    `is` `is not`    |    身份运算符    
12    |    `in` `not in`    |    成员运算符    
13    |    `not` `or` `and`   |    逻辑运算符 

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#! /usr/bin/env python
#coding=utf-8
#save file : operators_precedence_example.py

#!/usr/bin/python3

a = 20
b = 10
c = 15
d = 5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
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)

以上实例输出结果为:

1
2
3
4
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