Python 运算符优先级
pythonserver side programmingprogramming
下表列出了所有运算符,从最高优先级到最低优先级。
Sr.No | 运算符 &说明 |
---|---|
1 | ** 指数运算(提高幂) |
2 | ~ + - 补码、一元加法和减法(最后两个的方法名称为 +@ 和 -@) |
3 | * / % // 乘法、除法、取模和向下取整除法 |
4 | + - 加法和减法 |
5 | >> << 右移和左移 |
6 | & 按位"AND"td> |
7 | ^ | 按位异或和常规"OR" |
8 | <= < > >= 比较运算符p> |
9 | <> == != 相等运算符 |
10 | = %= /= //= -= += *= **= 赋值运算符 |
11 | is is not is is not |
12 | in not in 成员运算符 |
13 | not or and 逻辑运算符 |
运算符优先级影响表达式的求值方式。
例如,x = 7 + 3 * 2;这里,x 被赋值为 13,而不是 20,因为运算符 * 的优先级高于 +,所以它先乘以 3*2,然后加到 7。
这里,优先级最高的运算符出现在表格的顶部,优先级最低的运算符出现在底部。
示例
#!/usr/bin/python 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 Value of ((a + b) * c) / d is 90 Value of (a + b) * (c / d) is 90 Value of a + (b * c) / d is 50