Truthy、True、Falsey、False
比較は「真っぽさ(truthiness)」を判定しますが、truthy であることは必ずしも True そのものではありません。逆も同様に、falsey であることは False とは限りません。したがって、True/False そのものを確認するのか、truthy/falsey を確認するのかを区別して注意深く扱う必要があります。Python では、2つのものが同一かどうかを確認するために is 演算子が使えます。ここでは、前の演習と同じキー(species、flipper_length、body_mass、sex)に加えて、真偽値を持つ tracked キーを含む、ペンギンの詳細レコード用の辞書を使います。
単一のペンギンの詳細データが入った辞書 penguin_305_details を読み込み済みです。
この演習はコースの一部です
Python のデータ型
演習の手順
penguin_305_detailsのsexキーの truthiness を確認します。- もし真であれば、
sexがTrueかを調べ、結果をsex_is_trueに保存します。 sexキーとsex_is_trueを出力します。
- もし真であれば、
penguin_305_detailsのtrackedキーの truthiness を確認します。- もし真であれば、
trackedがTrueかを調べ、結果をtracked_is_trueに保存します。 trackedキーとtracked_is_trueを出力します。
- もし真であれば、
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Check the truthiness of penguin_305_details sex key
if ____["____"]:
# If true, check if sex is True and store it as sex_is_true
sex_is_true = penguin_305_details["sex"] ____ ____
# Print the sex key's value and sex_is_true
print(f"{____['____']}: {____}")
# Check the truthiness of penguin_305_details tracked key
if ____["____"]:
# If true, check if tracked is True and store it as tracked_is_true
tracked_is_true = penguin_305_details["tracked"] ____ ____
# Print the tracked key and tracked_is_true
print(f"{____['____']}: {____}")