python:AND执行的顺序

时间:2013-06-21 09:34:16

标签: python boolean-logic

如果我有以下内容:

if a(my_var) and b(my_var):
    do something

我是否可以假设b()仅在a()True的情况下进行评估?或者它可能先b()吗?

提问,因为评估b()会在a()False时导致异常。

4 个答案:

答案 0 :(得分:7)

仅当b()a(my_var)时才会评估

True,是的。如果and为假,则a(my_var)运算符会短路。

来自boolean operators documentation

  

表达式x and y首先评估x;如果x为false,则返回其值;否则,将评估y并返回结果值。

您可以使用在调用时打印内容的函数自行测试:

>>> def noisy(retval):
...     print "Called, returning {!r}".format(retval)
...     return retval
... 
>>> noisy(True) and noisy('whatever')
Called, returning True
Called, returning 'whatever'
'whatever'
>>> noisy(False) and noisy('whatever')
Called, returning False
False

Python将空容器和数字0值视为false:

>>> noisy(0) and noisy('whatever')
Called, returning 0
0
>>> noisy('') and noisy('whatever')
Called, returning ''
''
>>> noisy({}) and noisy('whatever')
Called, returning {}
{}

自定义类可以实现__nonzero__ hook以返回同一测试的布尔标志,或者如果它们是容器类型则实现__len__ hook;返回0表示容器为空,并被视为false。

在一个密切相关的说明中,or运算符执行相同的操作,但相反。如果第一个表达式的计算结果为true,则不会计算第二个表达式:

>>> noisy('Non-empty string is true') or noisy('whatever')
Called, returning 'Non-empty string is true'
'Non-empty string is true'
>>> noisy('') or noisy('But an empty string is false')
Called, returning ''
Called, returning 'But an empty string is false'
'But an empty string is false'

答案 1 :(得分:1)

是的,这样做是安全的。如果条件被懒惰地评估,则为蟒蛇。

答案 2 :(得分:1)

help()(哈)的精彩帮助下:

>>> help('and')

Boolean operations
******************

   or_test  ::= and_test | or_test "or" and_test
   and_test ::= not_test | and_test "and" not_test
   not_test ::= comparison | "not" not_test

...

The expression ``x and y`` first evaluates *x*; if *x* is false, its
value is returned; otherwise, *y* is evaluated and the resulting value
is returned.

...

是的,如果a(my_var)返回False,则不会调用函数b

答案 3 :(得分:0)

编译器始终从上到下,从左到右读取。所以If False and True然后编译器首先遇到False,它退出if条件。这适用于我所知道的所有软件。