运算符中的短路行为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