Dennis
Dennis

Reputation: 3678

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.)

Upvotes: 6

Views: 7915

Answers (2)

Maurice Meyer
Maurice Meyer

Reputation: 18106

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).

Upvotes: 9

IMCoins
IMCoins

Reputation: 3306

In python, you can use logic gates.

You can use either, for instance, and or &.

https://docs.python.org/2/library/stdtypes.html#bitwise-operations-on-integer-types

Upvotes: 0

Related Questions