Python3 一些与C++不一样的运算符

Python逻辑运算符
逻辑“与”运算符 and
逻辑表达式 a and b
如果变量a,b中有一个是Flase,那么a and b为Flase
如果变量a,b都为True,那么a and b为True

逻辑“或”运算符 or
逻辑表达式 a or b
如果变量a,b中最多只有一个是Flase,那么a or b为True
如果变量a,b都为Flase,那么a orb为Flase

逻辑“非”运算符 not
逻辑表达式 not a
如果变量a是Flase,那么not a为True
如果变量a是True,那么not a为Flase

在Spyder的Python console中输入如下代码

 a=1
 b=1
 a and b
 a or b
 not a

结果:
1
1
Flase

 a=0
 b=1
 a and b
 a or b
 not a

结果:
0
1
True

这样看其实Python的逻辑运算符和C++的并没有什么区别,但是如果我们不用0,1表示a,b

 a=5
 b=6
 a and b
 a or b
 not a

结果:
6
5
Flase

 a=0
 b=6
 a and b
 a or b
 not a

结果:
0
6
True

从上面的例子可以看到,“与”,“或”并没有像C++中严格的返回一个bool型的值,其次,在and中如果所有值均为真(结果为真),则返回最后一个值,若存在假,返回第一个假值;在or 中如果最终的结果为真,那么返回第一个真值,如果结果为假返回0。

Python成员运算符
成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。

运算符:in
描述:如果在指定的序列中找到值返回 True,否则返回 False。

运算符:not in
描述:如果在指定的序列中没有找到值返回 True,否则返回 False。

a = 10
b = 2
list = [1, 2, 3, 4, 5 ];
a in list
a not in list
b in list
b not in list

结果:
Flase
True
True
Flase

Python身份运算符

身份运算符用于比较两个对象的存储单元

运算符:is
描述:is 是判断两个标识符是不是引用自一个对象(相同的地址,相同的存储空间),是则为True,否则为Flase。

运算符:is not
描述:is not 是判断两个标识符是不是引用自不同对象(相同的地址,相同的存储空间),是则为True,否则为Flase。

a =1
b = 1
c = 2
a is b
a is not b
a is c
a is not c

结果:
True
Flase
Flase
True

你可能感兴趣的:(python,运算符)