Python | 文法の基本:真偽値(bool)

Python
スポンサーリンク

真偽値の概要(bool の基本)

Pythonの真偽値は True と False の2つだけで、条件分岐やループの「動かす/止める」を決める軸になります。型名は bool で、比較や論理演算の結果として自然に現れます。注意点として、True/False は先頭が大文字で、true/false と書くとエラーになります。


真偽値の作られ方(比較と判定の基本)

比較演算の結果は bool

数値や文字列を比較すると、結果は必ず bool になります。等価は ==、不等価は !=、大小は < > <= >= を使います。

age = 20
print(age >= 18)  # True
print(age < 18)   # False

name = "花子"
print(name == "花子")  # True
print(name != "太郎")  # True
Python

含有判定や接頭語判定

in で「含まれているか」、startswith/endswith で「始まり/終わり」を判定できます。

tags = ["python", "beginner"]
print("python" in tags)       # True
print("py" in "python")       # True
print("python".startswith("py"))  # True
print("python".endswith("on"))    # True
Python

真偽値の評価ルール(Truthy/Falsy を深掘り)

Pythonでは、値そのものが「真とみなされるか」「偽とみなされるか」を持っています。ifやwhileの条件に、そのまま置けるのが特徴です。

  • 真(Truthy)の代表例: 非ゼロの数値、非空の文字列・リスト・辞書・セット、任意のオブジェクト
  • 偽(Falsy)の代表例: 0、0.0、空文字 “”、空リスト []、空タプル ()、空辞書 {}、空セット set()、None、False
items = []
if items:           # 空リストは Falsy(False 相当)
    print("中身あり")
else:
    print("空です")  # ここが実行される

text = " "
if text.strip():    # 前後空白除去後に判定するのが安全
    print("非空")
Python

「Truthy/Falsyで簡潔に書ける」一方で、意図を曖昧にしやすい場面では比較を明示すると誤解を減らせます。

# 曖昧になりやすい例(0とNoneは両方Falsy)
limit = 0
if limit:
    ...
# 意図を明示
if limit is None:   # 値なし(未設定)を判定
    ...
elif limit == 0:    # 0という有効な値を判定
    ...
Python

論理演算子と短絡評価(and, or, not の重要ポイント)

論理演算子は複数条件の組み合わせに使います。Pythonの and/or は「短絡評価(ショートサーキット)」で、必要最小限しか評価しません。これが安全で効率的な書き方を支えます。

# and: 左がTrueなら右を評価、左がFalseなら右を見ずにFalse
age = 20
is_member = True
print(age >= 18 and is_member)  # True

# or: 左がTrueなら右を見ない、左がFalseなら右を評価
has_coupon = False
print(has_coupon or age >= 18)  # True
Python

短絡評価は副作用のある処理やコストの大きいチェックで効きます。

def heavy():
    print("重い処理")
    return True

fast = False
print(fast and heavy())  # fastがFalseなので heavy()は呼ばれない(安全・高速)
Python

not は「真偽を反転」します。読みやすさを優先し、二重否定は避け、条件を肯定形で書く方が保守しやすくなります。

is_empty = not items  # itemsが空ならTrue
Python

等価(==)と同一性(is)の違い

== は「値が等しいか」、is は「同じオブジェクトか(同一性)」を判定します。None と比較するときは is を使うのが慣例です。

a = [1, 2]
b = [1, 2]
c = a

print(a == b)  # True(値が同じ)
print(a is b)  # False(別オブジェクト)
print(a is c)  # True(同じもの)

value = None
print(value is None)  # True(Noneは同一性で判定)
Python

bool と数値の関係(落とし穴と利点)

bool は int のサブタイプで、True は 1、False は 0 として振る舞います。集計に便利ですが、「意図しない数値化」には注意しましょう。

print(True + 1)   # 2
print(False * 10) # 0

flags = [True, False, True]
print(sum(flags)) # 2(Trueの数を数えられる)
Python

「if x == True」といった冗長な書き方は避けます。条件式はそのまま使うのが読みやすいです。

is_ok = (age >= 18)
if is_ok:           # これで十分
    ...
# 悪い例: if is_ok == True:
Python

実用的なパターン(any/all と条件式の書き方)

any は「ひとつでも真なら True」、all は「すべて真なら True」。複数条件の集約や入力検証で強力です。

has = [False, False, True]
print(any(has))  # True

checks = [age >= 18, is_member, not suspended]
print(all(checks))  # 全部満たすならTrue
Python

条件式は「早期否定」で分岐を浅く保つと読みやすくなります。

def can_buy(age, stock):
    if age < 18:
        return False
    if stock <= 0:
        return False
    return True
Python

例題で身につける

例題1:入力のバリデーションと早期リターン

複数条件を短く安全に書く例です。

def is_valid_username(name: str) -> bool:
    if name is None:
        return False
    name = name.strip()
    if not name:
        return False
    return 2 <= len(name) <= 20

print(is_valid_username(" 太郎 "))  # True
print(is_valid_username(" "))       # False
print(is_valid_username(None))      # False
Python

例題2:割引適用の複合条件(and/or と短絡評価)

会員かクーポン所持で割引、ただし停止中ユーザーは不可。

def apply_discount(price: int, is_member: bool, has_coupon: bool, suspended: bool) -> int:
    if suspended:
        return price  # 停止中は即終了(短絡評価と同じ考え方)
    eligible = is_member or has_coupon
    return int(price * (0.9 if eligible else 1.0))

print(apply_discount(1000, True, False, False))   # 900
print(apply_discount(1000, False, True, False))   # 900
print(apply_discount(1000, False, False, True))   # 1000
Python

例題3:Truthy/Falsy を活かした「デフォルト値」選択

or は左が Truthy なら左、Falsy なら右を返します。短く書けますが「0 や空文字も Falsy」なので意図の確認が必須です。

def display_limit(limit):
    # 0 を有効値としたい場合は is None を使って判定を分ける
    label = limit if limit is not None else "未設定"
    print(label)

display_limit(0)        # 0 がそのまま出る(意図が伝わる)
display_limit(None)     # "未設定"
Python

例題4:True の数を数える(bool は int として集計可能)

複数フラグのうち「有効なものの数」を取りたい場面。

features = {
    "dark_mode": True,
    "beta": False,
    "analytics": True
}
count_enabled = sum(features.values())
print(count_enabled)  # 2
Python

まとめ

bool は「動作を決める二択のスイッチ」で、比較や論理演算から自然に生まれます。Truthy/Falsy の評価、短絡評価の性質、== と is の使い分け、bool が int として振る舞う点を押さえると、条件式がぶれずに安定します。曖昧になりやすい場面では「None と 0 の区別」「肯定形で書く」「早期否定で分岐を浅く」の3点を習慣化すると、読みやすさと安全性が大きく向上します。

タイトルとURLをコピーしました