Python 論理演算子(ブール演算)
pythonの論理演算子
x = True y = True print(x and y) # True print(x or y) # True print(not x) # False x = True y = False print(x and y) # False print(x or y) # True print(not x) # False x = False y = True print(x and y) # False print(x or y) # True print(not x) # True x = False y = False print(x and y) # False print(x or y) # False print(not x) # True
bool型以外の変数に対する論理演算
pythonの論理演算において、Falseとして処理される変数は次の通り。
- ブール型の False
- None型の None
- 整数型の 0
- 浮動小数点数型の 0.0
- 文字列型の 空文字列 ""
- リスト型の 空データ []
- タプル型の 空データ ()
- 辞書型の 空データ {}
上記以外は、Trueとして処理される。
x = 1 y = 2 if x and y: print("x and y = True") else: print("x and y = False") # x and y = True と出力される print(x and y) # 2 と出力 ※論理演算結果はブール型にならないので注意 x = 1 y = 0 if x and y: print("x and y = True") else: print("x and y = False") # x and y = False と出力される print(x and y) # 0 と出力 ※論理演算結果はブール型にならないので注意
bool()関数
bool()関数を用いると、
変数が論理演算においてTrue/Falseのどちらで処理されるか確認できる。
print(bool(2)) # True print(bool(0)) # False print(bool(1 and 2)) # True print(bool(1 and 0)) # False print(bool(1.2)) # True print(bool(0.0)) # False print(bool(None)) # False print(bool("abc")) # True print(bool("")) # False print(bool([3, 4, 5])) # True print(bool([])) # False print(bool((3.5, 2.1, 0.0))) # True print(bool(())) # False print(bool({1:"apple", 2:"orange", 3:"banana"})) # True print(bool({})) # False