>>> 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
>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False
链式比较中的短路行为:
此外,在Python中
比较可以任意链接;例如,x < y <= z等价于x < y and y <= z,除了y只被求值一次(但在这两种情况下,当x < y被发现为假时,z根本不被求值)。
>>> 5 > 6 > fun(3) # same as: 5 > 6 and 6 > fun(3)
False # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3) # 5 < 6 is True
executed # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7) # 4 <= 6 is True
executed # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3 # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False
< p > 编辑:
还有一点值得注意,:-逻辑__ABC0, or操作符在Python中返回的是操作数的价值,而不是布尔值(True或False)。例如:< / p >
操作x and y给出的结果是if x is false, then x, else y
与其他语言(如&&)不同,C语言中的||操作符返回0或1。
例子:
>>> 3 and 5 # Second operand evaluated and returned
5
>>> 3 and ()
()
>>> () and 5 # Second operand NOT evaluated as first operand () is false
() # so first operand returned