Python : bool 型は真理値を扱う型

TwitterFacebookHatena
  • 公開:2021-9-17
  • 更新:2023-10-26
  • 文章量:2219
  • Python

TL;DR

bool 型は int 型の派生クラスであり、bool 型の値は True と False 、2 つの組み込み定数だけである。条件を満たしているかどうか表現する等に使うことができる。

bool 型のポイント

issubclass(bool, int)
# True
  • bool 型は int 型の派生クラス
  • ブール演算を使うと、真理値を扱うことができる
  • 組み込み関数 bool()によって、すべてのオブジェクトが真理値判定可能
  • 組み込み関数 bool()を使えば、データ型を bool に変換できる

class bool([x]) — Python 3.9.4 ドキュメント

値「True」と「False」の扱い

次は全て False として扱われる。その他のものはすべて True とみなされる。

bool('') # False
bool(0) # False
bool(0.0) # False
bool([]) # False
bool(()) # False
bool({}) # False
bool(set()) # False

False だけでなく空データ構造かどうか調べている。

a = []
if a:
    print('something')
else:
    print('empty')

# empty

複数の比較が必要な場合は、in 演算子 を用いて判定できる。

a = 'abcde'
b = 'k'
b in a

# False

if と in を用いて判定。

a = 'abcdefghijklmn'
b = 'k'

if b in a:
    print('something')

# something

ブール演算

ブール演算を使うと、真理値を扱うことができる。ブール演算子は or, and, not の 3 つがある。

or

どちらか一方でも真であれば真

True or True
# True

True or False
# True

False or True
# True

False or False
# False

and

両方が真なら真

True and True
# True

True and False
# False

False and True
# False

False and False
# False

x = 5
3 < x and x <10 # True
(3 < x) and (x < 10) # True
3< x and x > 10 # False

1 個の変数に対する複数の比較を and する場合、and を省くことができる。

3 < x < 10
# True

3 < x < 10 < 100
# True

not

真なら偽、偽なら真

not True
# False

not False
# True
x = ['book']
y = []
x or y # x が真なので x が返る
# ['book']

True は 1、False は 0

True + 1 # 2
True + 2 # 3

False + 0 # 0
False + 1 # 1

True + True # 2
False + False # 0
True + False # 1

組み込み関数 bool()

組み込み関数 bool()を使えば、データ型を bool に変換できる。引数として任意の 1 個の値を受け付け、bool 型に変換した結果を返す。

False のケース

値が 0 の数値は False とみなされる。

値が 0 の数値は偽

bool(0)
# False

空のコンテナオブジェクトは偽

bool([])
# False

空文字は偽

bool('')
# False

False は偽

bool(False)
# False

True のケース

0 でない数値は True とみなされる。

True が入ると真

bool(True)
# True

マイナスの整数は真

bool(-1)
# True

偽にならないものは全て真

bool(['book'])
# True

文字が含まれている場合は真

'b' in 'book'

ゼロのコンテナオブジェクトが入ると真

bool([0])
# True

コンテナオブジェクトに None が入ると真

bool([None])
# True

特殊メソッド __bool__()

特殊メソッド __bool__() は、オブジェクトを真理値で評価する。オブジェクトは、デフォルトでは真と判定されるが、__bool__() を実装すると判定処理を変更することができる。

class A:
    def __init__(self, foo):
        self.foo = foo
    def __bool__(self):
       return bool(self.foo)
a = A([])
bool(a) # False

a = A([0])
bool(a) # True

Python : bool 型は真理値を扱う型