In Python 3, operator.or_ is equivalent to the bitwise |
, not the logical or
. Why is there no operator for the logical or
?
Python has three logical operators: and , or , and not .
The Python operator module is one of the inbuilt modules in Python, and it provides us with a lot of functions such as add(x, y), floordiv(x, y) etc., which we can use to perform various mathematical, relational, logical and bitwise operations on two input numbers.
There are mainly three types of logical operators in python : logical AND, logical OR and logical NOT.
The or
and and
operators can't be expressed as functions because of their short-circuiting behavior:
False and some_function()
True or some_function()
in these cases, some_function()
is never called.
A hypothetical or_(True, some_function())
, on the other hand, would have to call some_function()
, because function arguments are always evaluated before the function is called.
The logical or is a control structure - it decides whether code is being executed. Consider
1 or 1/0
This does not throw an error.
In contrast, the following does throw an error, no matter how the function is implemented:
def logical_or(a, b):
return a or b
logical_or(1, 1/0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With