python:命令和执行顺序
如果我有以下资料:python:命令和执行顺序,python,boolean-logic,Python,Boolean Logic,如果我有以下资料: if a(my_var) and b(my_var): do something 我是否可以假设只有当a()为True时才计算b()?或者它可以先执行b() 当a()为Falseb()时,询问因为计算b()将导致异常,只有当a(my_var)为True时,才会计算b(),是。如果a(my_var)错误,则和操作员短路 从: 表达式x和y首先计算x;如果x为false,则返回其值;否则,将计算y,并返回结果值 您可以使用调用时打印某些内容的函数自己进行测试: >
if a(my_var) and b(my_var):
do something
我是否可以假设只有当a()
为True
时才计算b()
?或者它可以先执行b()
当a()
为False
b()
时,询问因为计算b()
将导致异常,只有当a(my_var)
为True
时,才会计算b()
,是。如果a(my_var)
错误,则和操作员短路
从:
表达式x和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 {}
{}
自定义类可以实现一个为同一测试返回布尔标志,或者如果它们是容器类型,则可以实现一个;返回0
表示容器为空,将被视为false
在一个密切相关的注释中,或
操作符做相同的事情,但相反。如果第一个表达式的计算结果为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'
是的,这样做是安全的。python,如果条件是延迟计算的。编译器总是从上到下、从左到右读取。因此If False和True
编译器首先遇到False,然后退出If条件。这对我所知道的所有软件都是有效的。在(哈)的帮助下:
因此,如果a(my_var)
返回False,那么函数b
将不会被调用
>>> 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.
...