Pythonでの和または非および論理短絡

5896 ワード

Pythonでの和または非および論理短絡
python 3.7 Shawn文書:https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
記事の目次
  • Pythonにおける和または非および論理短絡
  • と非
  • 論理ショート
  • と非
  • Pythonにおける真値判定の例は、Pythonオブジェクト真値判定論理粗解と簡明例
  • を参照しても良い。
  • pythonでは、javaなどの静的なものとは少し違っています。
  • ダイナミック言語の特性から、pythonの和または非は、より多くの動作を実現することができます:
  • >>> print(0 or [1,2,3])
    [1, 2, 3]
    >>> print(0 and [])
    0
    >>> print(set() or True)
    True
    
  • pythonによるオブジェクトのブール判定は、オブジェクトベースの_u u u_uである。book()方法又は_ulen_()方法の場合は、ブール値ではなく判定対象となります。
  • は、以下の関数として和または非近似を理解することができる。
  • def BooleanNOT(x):
        # not x
        if x:
            return False
        else:
            return True
    
    
    def BooleanOR(x, y):
        # x or y
        if not x:
            return y
        else:
            return x
    
    def BooleanAND(x, y):
        # x and y
        if not x:
            return x
        else:
            return y
    
    
    論理ショート
  • は前のセクションによって、論理的な判断においては、判定対象ごとに実行されるわけではないことが直感的に分かります。
  • と演算の最初のオブジェクト値がfalseであると、第二のオブジェクトは省略されます。
  • または演算の最初のオブジェクト値がtrueであれば、第二の同じオブジェクトは省略されます。
  • このような論理演算機構による現象を論理短絡といいます。
    >>> def print_but_false():
    		print("print but false")
    		return False
    
    >>> True or print_but_false()
    True
    >>> False and print_but_false()
    False
    >>> print_but_false() and True
    print but false
    False
    >>>