【Python】Python中的短路逻辑

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值