python短路与_Python支持短路吗?

运算符中的短路行为and,or:

让我们首先定义一个有用的函数来确定是否执行某些操作。 一个接受参数的简单函数,打印一条消息并返回输入,不变。

>>> def fun(i):

... print "executed"

... return i

...

在下面的例子中,可以观察到Python的and,or运算符的短路行为:

>>> fun(1)

executed

1

>>> 1 or fun(1) # due to short-circuiting "executed" not printed

1

>>> 1 and fun(1) # fun(1) called and "executed" printed

executed

1

>>> 0 and fun(1) # due to short-circuiting "executed" not printed

0

注意:解释器认为以下值表示错误:

False None 0 "" () [] {}

功能中的短路行为:and,or:

Python的and和and函数也支持短路。 如文档中所示; 他们按顺序评估序列的每个元素,直到找到允许在评估中提前退出的结果。 请考虑以下示例来理解两者。

函数and检查是否有任何元素为True。 一旦遇到True,它就会停止执行并返回True。

>>> any(fun(i) for i in [1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值