"and"/ && 的两部分条件是否在一部分已经为假时停止?
Does a two parted condition with "and"/ && stop when one part is already false?
简化示例:
a = False
b = True
if a and b:
#do stuff
如果 a 已经被识别为 false,python 是否跳过检查 b,因为只有一个条件需要为 False 才能使整个语句为 False?
在我的例子中,我想检查数组的 3 个条件,但如果其中至少一个条件为假,我想停止(为了更好的运行时间)。我可以吗
if a and b and c:
#do stuff
还是我必须走很远的路
if a:
if b:
if c:
return True
else:
return False
else:
return False
else:
return False
或者是否有其他方法可以检查此类内容?
是的,Python 短路。
证明:
>>> int('ValueError')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ValueError'
>>>
>>> False and int('ValueError')
False
>>> True or int('ValueError')
True
是的,您上面描述的称为短路,python确实如此。
与or
操作的情况类似。
a or b
如果 a
为 True
,则 在 a
处短路,否则检查 b
。
简化示例:
a = False
b = True
if a and b:
#do stuff
如果 a 已经被识别为 false,python 是否跳过检查 b,因为只有一个条件需要为 False 才能使整个语句为 False?
在我的例子中,我想检查数组的 3 个条件,但如果其中至少一个条件为假,我想停止(为了更好的运行时间)。我可以吗
if a and b and c:
#do stuff
还是我必须走很远的路
if a:
if b:
if c:
return True
else:
return False
else:
return False
else:
return False
或者是否有其他方法可以检查此类内容?
是的,Python 短路。
证明:
>>> int('ValueError')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ValueError'
>>>
>>> False and int('ValueError')
False
>>> True or int('ValueError')
True
是的,您上面描述的称为短路,python确实如此。
与or
操作的情况类似。
a or b
如果 a
为 True
,则 在 a
处短路,否则检查 b
。