なんだかGoodVibes

日々の勉強メモです。

【Python】Falseと判定されるもの

こんにちは。
本日はPythonメモです。

概要

True、Falseってチェックを行う際に必ず使用します。
例えば、以下のような場合。

num = 3
if num == 3:
    print('numは3です。')
else:
    print('numは3ではありません。')

この場合は、numが3かどうかをチェックしているので、答えは
はい、そうです。いいえ、違います。のブール値になります。

でも、条件文に設定されるものの答えが
ブール値ではない場合があります。

Pythonで、ブール値ではないけれど、Falseと判定されるものが何なのか
本記事で見ていこうと思います。


Falseと判定されるもの

ブール値
item = False
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

False = False


None
item = None
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

None = False


整数の0
item = 0
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

0 = False


floatの0
item = 0.0
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

0.0 = False


空文字
item = ''
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

 = False


空のリスト
item = []
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

[] = False


空のタプル
item = ()
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

() = False


空の辞書
item = {}
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

{} = False


空の集合
item = set()
if item:
    print(str(item) + ' = True')
else:
    print(str(item) + ' = False')

実行結果は以下です。

set() = False



以上です。