1、python中哪些对象会被当成 False 呢?而哪些又是 True 呢?
在Python中,None、任何数值类型中的0、空字符串“”、空元组()、空列表[]、空字典{}都被当作False,还有自定义类型,如果实现了 __ nonzero __ () 或 __ len __ () 方法且方法返回 0 或False,则其实例也被当作False,其他对象均为True。
2、简单的逻辑运算
True and True ==> True
True and False ==> False
False and True ==> False
False and False ==> False
True or True ==> True
True or False ==> True
False or True ==> True
False or False ==> False
3. 短路逻辑
- 表达式从左至右运算,若 or 的左侧逻辑值为 True ,则短路 or 后所有的表达式(不管是 and 还是 or),直接输出 or 左侧表达式 。
- 表达式从左至右运算,若 and 的左侧逻辑值为 False ,则短路其后所有 and 表达式,直到有 or 出现,输出 and 左侧表达式到 or 的左侧,参与接下来的逻辑运算。
- 若 or 的左侧为 False ,或者 and 的左侧为 True, 则不能使用短路逻辑。
def fun():
print("hello, world")
>>> print(0 and fun()) # fun()函数被短路
0
>>> print(fun() and 0) # 先运行fun()函数,fun()函数无返回值None,故0被短路
hello, world
None
>>> print(1 and fun()) # fun()函数未被短路,运行fun函数,输出hello,world,再返回逻辑运算结果
hello, world
None
>>> print(0 or fun()) # fun()函数未被短路,运行fun函数,输出hello,world,再返回逻辑运算结果
hello, world
None
>>> print(fun() or 0) # fun()函数未被短路,运行fun函数,输出hello,world,再返回逻辑运算结果
hello, world
0
>>> print(1 or fun()) # fun()函数被短路
1
参考:https://www.cnblogs.com/an9wer/p/5475551.html