Python运算符

Python运算符(8)-运算符优先级

2020-03-14  本文已影响0人  复苏的兵马俑

Python语言支持以下类型的运算符:
  1、算术运算符
  2、比较(关系)运算符
  3、赋值运算符
  4、逻辑运算符
  5、位运算符
  6、成员运算符
  7、身份运算符
  8、运算符优先级

8、运算符优先级

以下表格列出了从最高到最低优先级的所有运算符:

运算符 描述 结合性
() 小括号
x[i] 或 x[i1: i2 [:i3]] 索引运算符
x.attribute 属性访问
** 指数 (最高优先级)
~,+,- 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
*,/,%,// 乘,除,取模和取整除
+,- 加法减法
>>,<< 右移,左移运算符
& 位 'AND'
^,| 位运算符
>=,>,<,<= 比较运算符
==,!= 等于运算符
=,%=,/=,//=,-=,+=,=,*= 赋值运算符
is,is not 身份运算符
in,not in 成员运算符
not 逻辑运算符 “非”
and 逻辑运算符 “与”
or 逻辑运算符 “或 ”(最低优先级)
exp1, exp2 逗号运算符

  *注:所谓结合性,就是当一个表达式中出现多个优先级相同的运算符时,先执行哪个运算符:先执行左边的叫左结合性,先执行右边的叫右结合性。

实例代码:

print('“(20 + 10) * 15 / 5” 运算结果为:{}'.format((20 + 10) * 15 / 5))
print('“((20 + 10) * 15) / 5” 运算结果为:{}'.format(((20 + 10) * 15) / 5))
print('“(20 + 10) * (15 / 5)” 运算结果为:{}'.format((20 + 10) * (15 / 5)))
print('“20 + (10 * 15) / 5” 运算结果为:{}'.format(20 + (10 * 15) / 5))
print('“2 > 1 and 1 < 4”的返回值为:{}'.format(2 > 1 and 1 < 4))
print('“2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2”的返回值为:{}'.format(2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2))
print('“3>4 or 4<3 and 1==1”的返回值为:{}'.format(3>4 or 4<3 and 1==1))
print('“1 < 2 and 3 < 4 or 1>2”的返回值为:{}'.format(1 < 2 and 3 < 4 or 1>2))
print('“2 > 1 and 3 < 4 or 4 > 5 and 2 < 1”的返回值为:{}'.format(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1))
print('“1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8”的返回值为:{}'.format(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8))
print('“1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6”的返回值为:{}'.format(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6))
print('“not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6”的返回值为:{}'.format(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6))

运行结果:

“(20 + 10) * 15 / 5” 运算结果为:90.0
“((20 + 10) * 15) / 5” 运算结果为:90.0
“(20 + 10) * (15 / 5)” 运算结果为:90.0
“20 + (10 * 15) / 5” 运算结果为:50.0
“2 > 1 and 1 < 4”的返回值为:True
“2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2”的返回值为:True
“3>4 or 4<3 and 1==1”的返回值为:False
“1 < 2 and 3 < 4 or 1>2”的返回值为:True
“2 > 1 and 3 < 4 or 4 > 5 and 2 < 1”的返回值为:True
“1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8”的返回值为:False
“1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6”的返回值为:False
“not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6”的返回值为:False
上一篇下一篇

猜你喜欢

热点阅读