Python支持短路吗?

时间:2010-04-05 18:19:55

标签: python boolean-logic short-circuiting

Python是否支持布尔表达式中的短路?

4 个答案:

答案 0 :(得分:264)

是的,andor运算符短路 - 请参阅the docs

答案 1 :(得分:166)

运营商andor

中的短路行为

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

>>> def fun(i):
...     print "executed"
...     return i
... 

在以下示例中,您可以观察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    ""    ()    []     {}

注意:解释程序将以下值视为false:

any()

功能中的短路行为:all()>>> any(fun(i) for i in [1, 2, 3, 4]) # bool(1) = True executed True >>> any(fun(i) for i in [0, 2, 3, 4]) executed # bool(0) = False executed # bool(2) = True True >>> any(fun(i) for i in [0, 0, 3, 4]) executed executed executed True

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

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

>>> 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

函数any()检查所有元素是否为True并在遇到False时立即停止执行:

x < y <= z

链式比较中的短路行为:

此外,在Python中

  

all();例如,x < y and y <= z相当于y,但z仅评估一次(但在x < y中,>>> 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 根本不评估True发现是假的)。

False

修改
另一个值得注意的要点: - Python中的逻辑Comparisons can be chained arbitrarily运算符返回操作数的而不是布尔值(x and y或{{1} })。例如:

  

操作if x is false, then x, else y给出结果&&

与其他语言不同,例如C中的||>>> 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 运算符返回0或1。

示例:

or

同样bool(value)运算符返回最左侧的值True == >>> 2 or 5 # left most operand bool(2) == True 2 >>> 0 or 5 # bool(0) == False and bool(5) == True 5 >>> 0 or () () 其他最正确的值(根据短路行为),例如:

'<unknown>'

那么,这有什么用呢? and, or中给出的一个示例用法由Magnus Lie Hetland提出:
假设用户应该输入他或她的名字,但可以选择不输入任何内容,在这种情况下,您要使用默认值In [171]: name = raw_input('Enter Name: ') or '<Unkown>' Enter Name: In [172]: name Out[172]: '<Unkown>' 。你可以使用if语句,但你也可以非常简洁地陈述:

'<unknown>'

换句话说,如果raw_input的返回值为true(不是空字符串),则将其分配给name(没有任何更改);否则,默认name会分配给{{1}}。

答案 2 :(得分:44)

是。在python解释器中尝试以下内容:

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

答案 3 :(得分:0)

是的,Python 确实支持布尔运算符的短路求值最小求值麦卡锡求值。它用于减少计算布尔表达式输出的评估次数。示例 -

基本功能

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

与输出

a
b
1

a 

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

或输出

a
3

a
b
4