Why aren't “and” and “or” operators in Python?

前端 未结 6 592
陌清茗
陌清茗 2021-02-07 00:32

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 sh

6条回答
  •  醉话见心
    2021-02-07 01:09

    Because they're control flow constructs. Specifically:

    • if the left argument to and evaluates to False, the right argument doesn't get evaluated at all
    • if the left argument to or evaluates to True, the right argument doesn't get evaluated at all

    Thus, 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 "", line 1, in 
    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.

提交回复
热议问题