メインコンテンツへスキップ
Lesson5 / 6

条件式の書き方のコツ

目次

1. このレッスンで学ぶこと

  • 読みやすい条件式の書き方
  • 条件式を簡潔にするテクニック
  • よくある条件パターン
  • パフォーマンスを考慮した書き方

2. 条件式の書き方のコツとは

条件式の書き方とは、if文で使う条件を読みやすく、保守しやすく書くためのテクニックです。適切な書き方により、バグを減らし、コードの品質を高めることができます。

良い条件式の特徴

特徴説明
明確何をチェックしているかが一目でわかるis_adult vs a >= 18
簡潔不要な複雑さがないif is_valid: vs if is_valid == True:
一貫性同じパターンで書かれている命名規則の統一
可読性他の人が読んでも理解できる変数名が意味を持つ

読みやすい条件式と読みにくい条件式

Python
# ❌ 読みにくい
if not (age < 18 or age >= 65) and score >= 60 and attendance > 0.8:
    print("合格")

# ✅ 読みやすい
is_working_age = 18 <= age < 65
has_passing_score = score >= 60
has_good_attendance = attendance > 0.8

if is_working_age and has_passing_score and has_good_attendance:
    print("合格")

条件式を改善する基本原則

  • 複雑な条件は変数に分割する
  • 意味のある変数名を使う
  • 不要な比較を避ける
  • 論理演算子を適切に使う

3. なぜ条件式の書き方が重要なのか?

条件式は読みやすさがとても重要です。複雑な条件式はバグの温床になります。

Python
# 読みにくい
if not (age < 18 or age >= 65) and score >= 60 and attendance > 0.8:
    print("合格")

# 読みやすい
is_working_age = 18 <= age < 65
has_passing_score = score >= 60
has_good_attendance = attendance > 0.8

if is_working_age and has_passing_score and has_good_attendance:
    print("合格")

適切な書き方を知ることで、バグを減らし、保守性を高められます。

💡 豆知識: 「読みやすいコードは良いコード」という格言があります。プログラミングでは、書くことよりも読むことの方が多いため、可読性は非常に重要です。


4. 基本的なテクニック

変数に意味のある名前を付ける

良い例:

Python
age = 25
score = 75

is_adult = age >= 18
is_passing = score >= 60

if is_adult and is_passing:
    print("合格")

悪い例:

Python
a = 25
s = 75

if a >= 18 and s >= 60:
    print("合格")

用途: 可読性向上、保守性向上


複雑な条件は変数に分ける

良い例:

Python
price = 5000
is_member = True
purchase_count = 10

qualifies_for_discount = is_member and purchase_count > 5
is_expensive = price >= 3000

if qualifies_for_discount or is_expensive:
    discount_rate = 0.1

悪い例:

Python
if (is_member and purchase_count > 5) or price >= 3000:
    discount_rate = 0.1

5. 真偽値の扱い

直接比較しない

良い例:

Python
is_valid = True

if is_valid:
    print("有効です")

if not is_valid:
    print("無効です")

悪い例:

Python
is_valid = True

if is_valid == True:  # 冗長
    print("有効です")

if is_valid == False:  # 冗長
    print("無効です")

空の判定

良い例:

Python
name = ""
items = []
score = 0

# 空文字列
if not name:
    print("名前が入力されていません")

# 空リスト
if not items:
    print("商品がありません")

# ゼロ
if score == 0:  # 0はFalsyだが、明示的に比較
    print("点数なし")

注意: 0とNoneと空文字列は区別する

Python
value = 0

# 悪い例
if not value:  # 0はFalsy
    print("値なし")  # 0でも表示される

# 良い例
if value is None:
    print("値なし")

6. 範囲の判定

チェーン比較を活用

良い例:

Python
age = 25

if 18 <= age < 65:
    print("労働年齢")

score = 75
if 70 <= score <= 79:
    print("B評価")

悪い例:

Python
if age >= 18 and age < 65:
    print("労働年齢")

in演算子で複数値をチェック

良い例:

Python
status = "pending"

if status in ["pending", "processing", "waiting"]:
    print("処理中です")

day = "土曜日"
if day in ["土曜日", "日曜日"]:
    print("休日です")

悪い例:

Python
if status == "pending" or status == "processing" or status == "waiting":
    print("処理中です")

7. 否定形の扱い

二重否定を避ける

良い例:

Python
is_valid = True

if is_valid:
    print("有効")

悪い例:

Python
is_not_invalid = True

if not is_not_invalid:  # わかりにくい
    print("無効")

notの位置

良い例:

Python
if not is_logged_in:
    print("ログインしてください")

# または
if is_logged_in == False:
    print("ログインしてください")

読みやすさ重視:

Python
# 場合によっては肯定形に変える
is_guest = not is_logged_in

if is_guest:
    print("ログインしてください")

8. 具体例

例1: 会員ステータスの判定

Python
# 良い書き方
purchase_amount = 5000
purchase_count = 8
is_member = True

is_vip = is_member and purchase_count >= 10
is_regular_member = is_member and not is_vip

if is_vip:
    discount = 0.2
elif is_regular_member:
    discount = 0.1
else:
    discount = 0

# 悪い書き方
if is_member and purchase_count >= 10:
    discount = 0.2
elif is_member and not (is_member and purchase_count >= 10):
    discount = 0.1
else:
    discount = 0

例2: アクセス権限のチェック

Python
# 良い書き方
is_admin = role == "admin"
is_owner = user_id == resource_owner_id
is_public = resource_visibility == "public"

can_access = is_admin or is_owner or is_public

if can_access:
    print("アクセス許可")
else:
    print("アクセス拒否")

# 悪い書き方
if role == "admin" or user_id == resource_owner_id or resource_visibility == "public":
    print("アクセス許可")
else:
    print("アクセス拒否")

例3: 営業時間の判定

Python
# 良い書き方
hour = 14
day = "月曜日"

is_weekday = day not in ["土曜日", "日曜日"]
is_business_hours = 9 <= hour < 18

is_open = is_weekday and is_business_hours

if is_open:
    print("営業中")
else:
    print("営業時間外")

9. 練習問題

問題1(基礎)⭐☆☆

以下の条件を変数に分けて読みやすくしてください:

Python
if age >= 18 and age < 65 and score >= 60:
    print("合格")
✅ 解答例
Python
age = 25
score = 75

is_working_age = 18 <= age < 65
is_passing = score >= 60

if is_working_age and is_passing:
    print("合格")

問題2(基礎)⭐☆☆

以下の条件をin演算子を使って簡潔にしてください:

Python
if day == "土曜日" or day == "日曜日" or day == "祝日":
    print("休日")
✅ 解答例
Python
day = "土曜日"

if day in ["土曜日", "日曜日", "祝日"]:
    print("休日")

問題3(応用)⭐⭐☆

以下のコードを読みやすく改善してください:

Python
if not (score < 60 or attendance < 0.8) and report_submitted == True:
    print("合格")
✅ 解答例
Python
score = 75
attendance = 0.85
report_submitted = True

has_passing_score = score >= 60
has_good_attendance = attendance >= 0.8

if has_passing_score and has_good_attendance and report_submitted:
    print("合格")

10. まとめ

このレッスンでは、条件式を読みやすく安全に書くためのコツを学びました。

  • 条件式は短く分割し、意味が伝わる形で書くことが重要です。
  • 括弧や変数名を活用すると、複雑な判定でも読みやすくなります。
  • 境界値や例外ケースを意識して条件を設計する必要があります。
  • 重複した判定は整理し、保守しやすい構造にすることが大切です。
  • 条件ごとのテストケースを用意すると、意図しない分岐を防げます。