Search code examples
pythonpython-2.7logical-operatorsequivalent

What's the equivalent of AndAlso (&&) and OrElse (||) logical operators in Python?


In .NET VB and C#, we can use AndAlso (&&), OrElse (||) for logical operations

How about in Python, what is the equivalent logical operators? are they only limited to 'and' and 'or'?

Updated: Below is the difference between And/Or and AndAlso/OrElse
Quoted from 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.)


Solution

  • Python already does this:

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

    Returns:

    foo
    True
    
    bar
    foo
    True
    

    There is no need for AndAlso or OrElse in Python, it evaluates boolean conditions lazily (docs).