逻辑运算符
逻辑运算符是对bool值就行操作的,返回的结果也是bool
and
: 且, 全为True,才会返回Trueor
:或,一个为True,则会返回Truenot
: 非, 取反
>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> not True
False
>>> not False
True
>>> not not True
True
>>> 1 and 1 # 等价于 True and True
1
>>> 'a' and 'b'
'b'
>>> 'a' or 'b'
'a'
>>> not 'a' # 等价于 not True
False
那么哪些被认为True,哪些被认为False?
- int float: 0被认为False, 非0被认为True
- 字符串: 空字符串会被认为False,
''
是False,'0'
是True
>>> [1] or []
[1]
>>> [] or [1]
[1]
>>> 'a' and 'b'
'b'
>>> '' and 'a'
''
想一想,为什么1 and 2
返回的是2?
因为计算机要知道表达式1 and 2
的结果,必须读到2才知道
再看个例子
>>> 0 and 1
0
读了第一个数字,已经知道了结果,为提高计算机性能,就没有必要继续读了