Python语言支持以下类型的运算符:
Python算术运算符

Python比较运算符

Python赋值运算符

Python位运算符

Python逻辑运算符

Python成员运算符

Python身份运算符

s 与 == 区别:
is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等
Python运算符优先级

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/python3 a = 20 b = 10 c = 15 d = 5 e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5print ( "(a + b) * c / d 运算结果为:" , e)
e = ((a + b) * c) / d # (30 * 15 ) / 5 print ( "((a + b) * c) / d 运算结果为:" , e)
e = (a + b) * (c / d); # (30) * (15/5) print ( "(a + b) * (c / d) 运算结果为:" , e)
e = a + (b * c) / d; # 20 + (150/5) print ( "a + (b * c) / d 运算结果为:" , e)
|
2 进制是以 0b 开头的: 例如: 0b11 则表示十进制的 3
8 进制是以 0o 开头的: 例如: 0o11 则表示十进制的 9
16 进制是以 0x 开头的: 例如: 0x11 则表示十进制的 17
python 中的 and 从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值;
or 也是从左到有计算表达式,返回第一个为真的值;
其中数字 0 是假,其他都是真;
字符 "" 是假,其他都是真;
如果不用 a = b 赋值,int 型时,在数值为 -5~256(64位系统)时,两个变量引用的是同一个内存地址,其他的数值就不是同一个内存地址了。
也就是,a b 在 -5~256(64位系统)时:
a = 100 b = 100 a is b # 返回 True
a = 100
b = 100
a is b # 返回 True
其他类型如列表、元祖、字典让 a、b 分别赋值一样的时:
a is b # 返回False
a is b # 返回False
1、当列表,元组,字典中的值都引用 a,b 时,总是返回 True,不受 a,b 值大小的影响
a=1000 b=1000 list1=[a,3,5] list2=[b,4,5] print(list1[0] is list2[0]) tuple1=(a,3,5) tuple2=(b,4,5) print(tuple1[0] is tuple2[0]) dict1={6:a,2:3,3:5} dict2={1:b,2:4,3:7} print(dict1[6] is dict2[1])
a=1000
b=1000
list1=[a,3,5]
list2=[b,4,5]
print(list1[0] is list2[0])
tuple1=(a,3,5)
tuple2=(b,4,5)
print(tuple1[0] is tuple2[0])
dict1={6:a,2:3,3:5}
dict2={1:b,2:4,3:7}
print(dict1[6] is dict2[1])
输出结果为:
True True True
True
True
True
2、当不引用a,b,直接用具体值来测试时,列表,字典,不受值大小影响,返回True,元组则受 256 值范围的影响,超出范围则地址改变,返回 False。
list1=[1000,3,5] list2=[1000,4,5] print(list1[0] is list2[0]) tuple1=(1000,3,5) tuple2=(1000,4,5) print(tuple1[0] is tuple2[0]) dict1={6:1000,2:3,3:5} dict2={1:1000,2:4,3:7} print(dict1[6] is dict2[1])
list1=[1000,3,5]
list2=[1000,4,5]
print(list1[0] is list2[0])
tuple1=(1000,3,5)
tuple2=(1000,4,5)
print(tuple1[0] is tuple2[0])
dict1={6:1000,2:3,3:5}
dict2={1:1000,2:4,3:7}
print(dict1[6] is dict2[1])
输出结果为:
True False True
True
False
True
3、当直接用列表、元组、字典本身来测试时,刚好相反,元组返回 True,列表,字典返回 False。
list1=[1000,3,5] list2=[1000,3,5] print(list1 is list2) tuple1=(1000,3,5) tuple2=(1000,3,5) print(tuple1 is tuple2) dict1={1:1000,2:3,3:5} dict2={1:1000,2:3,3:5} print(dict1 is dict2)
list1=[1000,3,5]
list2=[1000,3,5]
print(list1 is list2)
tuple1=(1000,3,5)
tuple2=(1000,3,5)
print(tuple1 is tuple2)
dict1={1:1000,2:3,3:5}
dict2={1:1000,2:3,3:5}
print(dict1 is dict2)
输出结果为:
False True False
False
True
False
1.or
在 Python 中,逻辑运算符 or,x or y, 如果 x 为 True 则返回 x,如果 x 为 False 返回 y 值。因为如果 x 为 True 那么 or 运算就不需要在运算了,因为一个为真则为真,所以返回 x 的值。如果 x 的值为假,那么 or 运算的结果取决于 y,所以返回 y 的值。
2.and
在 Python 中,逻辑运算符 and,x and y,如果 x 为 True 则返回 y 值。如果 x 为 False 则返回 y 值。如果 x 的值为 True,and 的运算不会结束,会继续看 y 的值,所以此时真与假取决于 y 的值,所以 x 如果为真,则返回 y 的值。如果 x 为假,那么 and 运算就会结束运算过程了,因为有一个为假则 and 为假,所以返回 x 的值。
3.混合例子与解析
按照从左向由,优先级高的先执行优先级高的规则,首先因为比较运算符优先级高于逻辑运算符,很简单,如果运算符低于了逻辑运算符优先级那还如何运算呢。and 优先级大于 or,not 优先级大于 and 和 or。