Python运算符优先级
1、and比or的优先级
在没有()的情况下not 优先级高于 and,and优先级高于or,即优先级关系为( )>not>and>or,同一优先级从左往右计算。
运算符 | 描述 |
---|---|
** | 指数 (最高优先级) |
~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) |
* / % // | 乘,除,取模和取整除 |
+ - | 加法减法 |
>> << | 右移,左移运算符 |
& | 位 'AND' |
^ | | 位运算符 |
<= < > >= | 比较运算符 |
<> == != | 等于运算符 |
= %= /= //= -= += *= **= | 赋值运算符 |
is is not | 身份运算符 |
in not in | 成员运算符 |
not and or | 逻辑运算符 |
以下几个例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 print(3>4 or 4<3 and 1==1) 2 print(1 < 2 and 3 < 4 or 1>2) 3 print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1) 4 print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8) 5 print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) 6 print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) 7 8 输出结果: 9 False 10 True 11 True 12 False 13 False 14 False
2、or 及 and的运算结果:
x or y , x为真,值就是x,x为假,值是y;
x and y, x为真,值是y,x为假,值是x。
例如:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 m1 = 8 or 4 2 m2 = 0 and 3 3 m3 = 0 or 4 and 3 or 7 or 9 and 6 4 print(m1) 5 print(m2) 6 print(m3) 7 8 结果为: 9 8 10 0 11 3
3、成员运算符 in、not in
可以用在子字符串是否在目标字符串(包括元组、字典、集合等)中
例如:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 print("早起" in "我每天都早起") 2 print("peng" in "pengjunfei") 3 print("peng" in "junfei") 4 print("peng" not in "junfei") 5 6 结果: 7 True 8 True 9 False 10 True
4、=、==、is 、id()、小数据池等小知识点
= : 赋值;
== : 比较值是否相等;
is :比较的是内存地址;
id():求括号里的内容;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 li2 = [1,2,3,4] 2 li3 = li2 3 print(id(li2),id(li3)) 4 li2 = [1,2,3,4] 5 print(id(li2),id(li3)) 6 7 结果: 8 43657416 43657416 9 43508680 43657416
#数字、字符串的小数据池:就是为了一定程度范围内节省内存空间
#数据的范围:-5-----256
#字符串的范围:1, 不能有特殊字符(表示怀疑这一说法)
2、 s *20,不能超过20个字符;
# 对于list dict tuple set不具备小数据池概念
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 li1 = 5 2 li2 = 5 3 print(id(li1),id(li2)) 4 结果: 5 1473732896 1473732896
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 li3 = 'peng' 2 li4 = 'peng' 3 print(li3 is li4) 4 5 li5 = 'peng@++=' 6 li6 = 'peng@++=' 7 print(li5 is li6) 8 9 s1 = 'a'*20 10 s2 = 'a'*20 11 print(s1 is s2) 12 13 s1 = 'a'*21 14 s2 = 'a'*21 15 print(s1 is s2) 16 结果: 17 True 18 True 19 True 20 False