Pythonでプログラムを書くとき、避けて通れないのが条件式です。
「もし○○なら△△する」という分岐は、あらゆる場面で必要になります。
条件式が活躍する場面:
- ユーザーの入力に応じた処理の切り替え
- エラーハンドリング(異常な値の検出)
- データの分類・フィルタリング
- ゲームやアプリのロジック実装
- 設定に応じた動作の変更
具体例:
# ユーザーの年齢に応じた処理
age = int(input("年齢を入力してください: "))
if age >= 18:
print("成人です")
else:
print("未成年です")
この記事では、Pythonにおける条件式(if文)の基本から応用的な書き方、三項演算子の活用法や複数条件の書き方まで、初心者の方にも分かりやすく解説していきます。
第1章:Pythonの基本的な条件式(if文)の書き方

基本構文
if 条件:
条件がTrueの時に実行する処理
重要なポイント:
- 条件の後には必ずコロン(:)を付ける
- 実行する処理はインデント(字下げ)で表現
- Pythonでは通常半角スペース4つでインデントする
基本的な例
score = 80
if score >= 70:
print("合格です")
print("おめでとうございます!")
print("判定終了") # インデントなし = if文の外
出力結果:
合格です
おめでとうございます!
判定終了
インデントの重要性
# 正しい例
if True:
print("これは表示される")
print("これも表示される")
# 間違った例(インデントエラーになる)
if True:
print("エラーになる") # IndentationError
if-else構文
ifの条件を満たさなかった場合の処理は、if-else構文を使う。
score = 60
if score >= 70:
print("合格")
else:
print("不合格")
print("もう一度頑張りましょう")
動作の流れ:
- 条件
score >= 70
を評価 - Trueなら
if
ブロックを実行 - Falseなら
else
ブロックを実行
実用的な例
def check_password(password):
"""パスワードの強度チェック"""
if len(password) >= 8:
print("パスワードは十分な長さです")
return True
else:
print("パスワードが短すぎます(8文字以上にしてください)")
return False
# 使用例
user_password = "secret123"
is_valid = check_password(user_password)
第2章:複数条件を扱う|elifと論理演算子
if-elif-elseの構文
ifで満たさなかった場合を、elifでさらに条件分岐できる。
if 条件1:
処理1
elif 条件2:
条件1がfalseで、条件2を満たすときの処理2
elif 条件3:
条件1と2がFalseで、条件3を満たす時の処理3
else:
どの条件にも当てはまらないときの処理
成績判定の例
score = 85
if score >= 90:
grade = "A"
print("素晴らしい成績です!")
elif score >= 80:
grade = "B"
print("良い成績です")
elif score >= 70:
grade = "C"
print("合格です")
elif score >= 60:
grade = "D"
print("ギリギリ合格です")
else:
grade = "F"
print("不合格です")
print(f"あなたの成績: {grade}")
論理演算子の基本
演算子 | 意味 | 例 |
---|---|---|
and | 両方がTrueの場合にTrue | if x > 0 and x < 10: |
or | どちらかがTrueの場合にTrue | if x < 0 or x > 10: |
not | True/Falseを反転 | if not x == 0: |
論理演算子の実用例
def can_vote(age, is_citizen):
"""投票資格チェック"""
if age >= 18 and is_citizen:
return True
else:
return False
def is_weekend(day):
"""週末かどうかチェック"""
if day == "土曜日" or day == "日曜日":
return True
else:
return False
def is_valid_email(email):
"""簡単なメールアドレス検証"""
if "@" in email and "." in email and not email.startswith("@"):
return True
else:
return False
# 使用例
print(can_vote(20, True)) # True
print(is_weekend("月曜日")) # False
print(is_valid_email("test@example.com")) # True
複雑な条件の組み合わせ
def check_discount_eligibility(age, is_student, purchase_amount):
"""割引対象かどうかを判定"""
if (age >= 65 or is_student) and purchase_amount >= 1000:
discount_rate = 0.2 # 20%割引
elif age >= 65 or is_student:
discount_rate = 0.1 # 10%割引
elif purchase_amount >= 5000:
discount_rate = 0.15 # 15%割引
else:
discount_rate = 0 # 割引なし
return discount_rate
# 使用例
rate = check_discount_eligibility(age=70, is_student=False, purchase_amount=1500)
print(f"割引率: {rate * 100}%") # 割引率: 20.0%
in演算子を使った条件
# リストや文字列に含まれているかチェック
valid_colors = ["red", "blue", "green", "yellow"]
user_choice = "blue"
if user_choice in valid_colors:
print(f"{user_choice}は有効な色です")
else:
print("無効な色が選択されました")
# 文字列内の文字チェック
password = "abc123"
if "@" in password or "#" in password:
print("特殊文字が含まれています")
else:
print("特殊文字が含まれていません")
第3章:Pythonならではの条件式の省略記法

三項演算子(条件式)
基本構文:
値1 if 条件 else 値2
基本例:
score = 90
result = "合格" if score >= 70 else "不合格"
print(result) # 合格
# 従来のif-else文との比較
if score >= 70:
result = "合格"
else:
result = "不合格"
三項演算子の実用例
# 年齢に応じたメッセージ
age = 25
message = "成人です" if age >= 18 else "未成年です"
# 数値の正負判定
number = -5
sign = "正の数" if number > 0 else "負の数または0"
# リストの要素数チェック
items = [1, 2, 3]
status = "データあり" if len(items) > 0 else "データなし"
# 関数の戻り値での使用
def get_max(a, b):
return a if a > b else b
print(get_max(10, 20)) # 20
ネストした三項演算子(注意して使用)
score = 85
# 複数段階の判定
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # B
# 読みやすさを重視するなら通常のif-elif文を推奨
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
条件付きリスト内包表記
# 基本的なフィルタリング
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers) # [2, 4, 6, 8, 10]
# 条件付きで値を変換
original = [1, 2, 3, 4, 5]
modified = [x * 2 if x % 2 == 0 else x for x in original]
print(modified) # [1, 4, 3, 8, 5]
# 複数条件でのフィルタリング
students = [
{"name": "Alice", "age": 20, "grade": 85},
{"name": "Bob", "age": 22, "grade": 75},
{"name": "Charlie", "age": 19, "grade": 95}
]
honor_students = [
student["name"]
for student in students
if student["age"] >= 20 and student["grade"] >= 80
]
print(honor_students) # ['Alice']
条件付き辞書内包表記
# 条件に応じた辞書作成
numbers = range(1, 6)
square_dict = {n: n**2 for n in numbers if n % 2 == 1}
print(square_dict) # {1: 1, 3: 9, 5: 25}
# より複雑な例
products = [
{"name": "Apple", "price": 100},
{"name": "Banana", "price": 50},
{"name": "Cherry", "price": 200}
]
expensive_products = {
item["name"]: item["price"]
for item in products
if item["price"] > 80
}
print(expensive_products) # {'Apple': 100, 'Cherry': 200}
第4章:条件式でよくあるミスと注意点
よくある間違いパターン
1. 代入演算子(=)と比較演算子(==)の混同
# 間違い
x = 5
if x = 10: # SyntaxError
print("これはエラー")
# 正しい
if x == 10:
print("xは10です")
2. インデントのミス
# 間違い:インデントが一致していない
if True:
print("1行目")
print("2行目") # IndentationError
# 正しい
if True:
print("1行目")
print("2行目")
3. 真偽値の誤解
# Falseとして扱われる値
falsy_values = [False, 0, 0.0, "", [], {}, None]
for value in falsy_values:
if value:
print(f"{value} は True")
else:
print(f"{value} は False") # すべてこちらが実行される
# 空のリストのチェック
my_list = []
if my_list:
print("リストに要素があります")
else:
print("リストは空です") # これが実行される
# 正しい要素数チェック
if len(my_list) > 0:
print("リストに要素があります")
4. 比較演算子の連結を知らない
# Pythonでは範囲チェックが簡単
x = 5
# 他の言語的な書き方
if x > 0 and x < 10:
print("0より大きく10未満")
# Pythonらしい書き方
if 0 < x < 10:
print("0より大きく10未満")
# より複雑な例
score = 85
if 80 <= score <= 90:
print("B評価の範囲内")
パフォーマンスに関する注意点
# 短絡評価(Short-circuit evaluation)の活用
def expensive_function():
print("重い処理を実行中...")
return True
# and演算子:左側がFalseなら右側は評価されない
if False and expensive_function():
print("実行されない")
# "重い処理を実行中..."は表示されない
# or演算子:左側がTrueなら右側は評価されない
if True or expensive_function():
print("実行される")
# "重い処理を実行中..."は表示されない
# 条件の順序を工夫してパフォーマンス向上
def check_user_permission(user):
# 軽い処理を先に、重い処理を後に
if user.is_active and user.has_valid_subscription() and user.check_database_permission():
return True
return False
デバッグのためのベストプラクティス
# 条件をわかりやすい変数に分ける
def process_order(user, product, quantity):
# 可読性の悪い例
if user.age >= 18 and user.has_credit_card and product.in_stock and quantity > 0 and quantity <= product.max_order:
return "注文処理"
# 可読性の良い例
is_adult = user.age >= 18
has_payment_method = user.has_credit_card
is_available = product.in_stock
is_valid_quantity = 0 < quantity <= product.max_order
if is_adult and has_payment_method and is_available and is_valid_quantity:
return "注文処理"
else:
# エラーの詳細を特定しやすい
if not is_adult:
return "年齢制限エラー"
elif not has_payment_method:
return "決済方法エラー"
# ...
第5章:実践的な条件式の活用例

関数での条件式活用
def calculate_shipping_fee(weight, distance, is_premium):
"""配送料計算"""
base_fee = 500
# 重量による追加料金
if weight > 10:
weight_fee = (weight - 10) * 100
else:
weight_fee = 0
# 距離による係数
if distance < 50:
distance_multiplier = 1.0
elif distance < 100:
distance_multiplier = 1.5
else:
distance_multiplier = 2.0
total_fee = (base_fee + weight_fee) * distance_multiplier
# プレミアム会員は20%割引
if is_premium:
total_fee *= 0.8
return int(total_fee)
# 使用例
print(calculate_shipping_fee(15, 75, True)) # 1200
クラスでの条件式活用
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
self.is_frozen = False
def withdraw(self, amount):
"""出金処理"""
if self.is_frozen:
return "アカウントが凍結されています"
if amount <= 0:
return "出金額は正の数である必要があります"
if amount > self.balance:
return "残高不足です"
self.balance -= amount
return f"出金成功: {amount}円"
def deposit(self, amount):
"""入金処理"""
if self.is_frozen:
return "アカウントが凍結されています"
if amount <= 0:
return "入金額は正の数である必要があります"
self.balance += amount
return f"入金成功: {amount}円"
# 使用例
account = BankAccount(1000)
print(account.withdraw(500)) # 出金成功: 500円
print(account.withdraw(600)) # 残高不足です
エラーハンドリングでの活用
def safe_divide(a, b):
"""安全な除算関数"""
# 入力値の型チェック
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
return "エラー: 数値を入力してください"
# ゼロ除算チェック
if b == 0:
return "エラー: ゼロで割ることはできません"
result = a / b
# 結果の範囲チェック
if abs(result) > 1e10:
return "警告: 結果が非常に大きな値です"
return result
# 使用例
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # エラー: ゼロで割ることはできません
print(safe_divide("10", 2)) # エラー: 数値を入力してください
まとめ
Pythonの条件式は、分かりやすく、読みやすく、書きやすいという特徴があります。
基本のif-else
から、elif
や論理演算子、三項演算子までをマスターすれば、日常的なプログラムの90%以上の分岐処理が可能になります。
本記事の重要ポイント
基本的な構文:
if
文:基本の分岐処理elif
:複数条件の処理else
:上記のどれにも当てはまらない場合- 論理演算子:
and
、or
、not
で条件を組み合わせ
Pythonらしい書き方:
- 三項演算子:
値1 if 条件 else 値2
で簡潔な記述 - 比較の連結:
0 < x < 10
のような直感的な範囲チェック - 条件付き内包表記:リストや辞書の効率的な生成
注意すべきポイント:
==
と=
の使い分け:比較には==
、代入には=
- インデント:半角スペース4つで統一
- 真偽値の理解:空のコンテナやゼロは
False
- 可読性:複雑な条件は変数に分けて分かりやすく
コメント