Python | 文法の基本:論理演算子

Python
スポンサーリンク

論理演算子の概要

Pythonの論理演算子は and(論理積)、or(論理和)、not(否定)の3つです。条件式を組み合わせて「複雑な判定」を短く、読みやすく表現できます。結果は必ず真偽値(True/False)で、if文やwhile文の分岐に直結します。


基本の意味と短絡評価(ショートサーキット)

and, or, not の基本

  • and は両方が True のときだけ True。or はどちらかが True なら True。not は真偽を反転します。直感どおりに使えるため、複数条件の組み立てに最適です。
age = 20
is_member = True
print(age >= 18 and is_member)  # True
print(is_member or age >= 100)  # True
print(not is_member)            # False
Python

短絡評価の性質(ここが重要)

and と or は「必要最小限しか評価しない」短絡評価を行います。and は左が False なら右を評価せずに False、or は左が True なら右を評価せずに True。これはエラー回避や無駄な処理の削減に役立ちます。

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

fast_check = False
print(fast_check and heavy())  # 左が False → heavy() は呼ばれない
Python

Truthy/Falsy と安全な条件の書き方

値そのものの真偽評価

Pythonでは、0、空文字、空のコンテナ、None、False は「偽(Falsy)」として扱われ、非ゼロや非空は「真(Truthy)」になります。この性質を活かすと、条件式を短く書けます。

items = []
if not items:     # 空ならTrue
    print("空です")

text = "  "
if text.strip():  # 前後空白を除去して非空か評価
    print("入力あり")
Python

None と 0 の区別(曖昧さを避ける)

0 も Falsy、None も Falsy なので、設定値と未設定の違いを明確にするには is を使って None を判定し、値の有効性は別途比較します。

limit = None
if limit is None:
    print("未設定")
elif limit == 0:
    print("0は有効値")
Python

演算子の優先順位と括弧

not > and > or の順

論理演算子は、not が最も強く、次に and、最後に or が評価されます。括弧で意図を明示すると、読み手の誤解やバグを避けられます。

a, b, c = True, False, True
print(a or b and c)      # 実際は a or (b and c)
print((a or b) and c)    # 意図を括弧で固定
Python

デ・モルガンの法則で読みやすく

複雑な否定は、not (A and B) を (not A) or (not B) に、not (A or B) を (not A) and (not B) に書き換えると読みやすくなります。

def can_run(is_admin, is_active):
    # どちらかがFalseなら実行不可
    return not (not is_admin or not is_active)  # = is_admin and is_active
Python

返り値のふるまいと活用テクニック

and/or の「そのまま返す」性質

Pythonの and/or は真偽値だけでなく「オペランドそのもの」を返すため、デフォルト値選択に応用できます。or は左が Truthy なら左、Falsy なら右を返します。過度なトリックは避け、読みやすさを優先しましょう。

username = input("名前: ").strip()
label = username or "ゲスト"  # 空なら "ゲスト"
print(label)
Python

any/all で複数条件を集約

any はひとつでも True なら True、all はすべて True なら True。複数チェックを配列にして集約すると、状態管理がすっきりします。

age = 22
is_member = True
not_suspended = True

if all([age >= 18, is_member, not_suspended]):
    print("購入可能")
Python

例題で身につける

例題1:安全な入力バリデーション(短絡評価で守る)

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

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

短絡評価により、左側で False が決まれば右側の評価(例えば重い処理)を行いません。条件を安全に並べると、無駄な計算や例外を避けられます。

例題2:アクセス権限の複合条件(not と括弧で明確化)

def can_access(is_admin: bool, is_staff: bool, locked: bool) -> bool:
    return (is_admin or is_staff) and not locked

print(can_access(True, False, False))  # True
print(can_access(False, True, True))   # False
Python

not の優先順位が高いため、否定の対象は括弧で明示すると誤読を防げます。

例題3:デフォルト値の選択(or の性質を利用)

def display_limit(limit: int | None):
    label = limit if limit is not None else "未設定"
    print(label)

display_limit(0)     # 0 を有効値として扱う
display_limit(None)  # "未設定"
Python

0 や空文字は Falsy なので、or に頼ると「有効な 0 まで置き換え」てしまう落とし穴があります。None を明示判定して意図を伝えます。

例題4:any/all でチェックを整理

def can_buy(age: int, stock: int, suspended: bool) -> bool:
    if suspended:
        return False
    return all([age >= 18, stock > 0])

print(can_buy(20, 5, False))  # True
print(can_buy(17, 5, False))  # False
Python

複数条件をリストにして all/any で評価すると、要件の見通しが良くなります。


まとめ

論理演算子は「複数条件を安全かつ読みやすく組み立てる」ための核です。短絡評価で無駄な処理を避け、not > and > or の優先順位を理解し、括弧で意図を固定します。Truthy/Falsy の評価は便利ですが、None と有効な 0 の区別など曖昧さに注意。and/or の返り値の性質、any/all の集約を使いこなすと、実務の判定ロジックがシンプルに整理できます。

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