Skip to main content
 首页 » 编程设计

python之Python 中 AndAlso (&&) 和 OrElse (||) 逻辑运算符的等效项是什么

2024年10月01日6telwanggs

在.NET VB和C#中,我们可以使用AndAlso(&&)、OrElse(||)进行逻辑运算

Python 中,等价的逻辑运算符是什么?它们是否仅限于“and”和“or”?

更新:下面是And/Or和AndAlso/OrElse的区别
引自 https://stackoverflow.com/a/8409488/719998

Or/And will always evaluate both1 the expressions and then return a result. They are not short-circuiting evaulation.

OrElse/AndAlso are short-circuiting. The right expression is only evaluated if the outcome cannot be determined from the evaluation of the left expression alone. (That means: OrElse will only evaluate the right expression if the left expression is false, and AndAlso will only evaluate the right expression if the left expression is true.)

请您参考如下方法:

Python 已经这样做了:

def foo(): 
    print ("foo") 
    return True 
 
def bar(): 
    print ("bar") 
    return False 
 
 
print (foo() or bar()) 
print ("") 
print (bar() or foo()) 

返回:

foo 
True 
 
bar 
foo 
True 

Python 中不需要 AndAlso 或 OrElse,它会延迟计算 bool 条件 ( docs )。