I wasn't aware of this, but apparently the and
and or
keywords aren't operators. They don't appear in the list of python operators. Just out of sheer curiosity, why is this? And if they aren't operators, what exactly are they?
In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not.
Because, in Python, integers are immutable (int's += actually returns a different object). Also, with ++/-- you need to worry about pre- versus post- increment/decrement, and it takes only one more keystroke to write x+=1 . In other words, it avoids potential confusion at the expense of very little gain.
There are three Boolean operators in Python: and , or , and not . With them, you can test conditions and decide which execution path your programs will take.
Because they're control flow constructs. Specifically:
and
evaluates to False, the right argument doesn't get evaluated at allor
evaluates to True, the right argument doesn't get evaluated at allThus, it is not simply a matter of being reserved words. They don't behave like operators, since operators always evaluate all of their arguments.
You can contrast this with bitwise binary operators which, as the name implies, are operators:
>>> 1 | (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>> 1 or (1/0) 1
As you see, the bitwise OR (|
) evaluates both its arguments. The or
keyword, however, doesn't evaluate its right argument at all when the left argument evaluates to True; that's why no ZeroDivisionError
is raised in the second statement.
Python does not currently provide any 'xxx' special methods corresponding to the 'and', 'or' and 'not' boolean operators. In the case of 'and' and 'or', the most likely reason is that these operators have short-circuiting semantics, i.e. the second operand is not evaluated if the result can be determined from the first operand. The usual technique of providing special methods for these operators therefore would not work.
Source: PEP 335
PEP 335 talks about adding the ability to have overloadable operators, and discusses this issue a bit.
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