Python制御構文完全まとめ!if文・for文・while文の使い方【2025年最新版】
Pythonを学び始めたけど、if文やfor文、while文の使い分けが分からないと悩んでいませんか?制御構文は、プログラムの流れを制御する基本的で重要な文法です。この記事では、Python初心者でも理解できるように、制御構文の基本から実践的な使い方まで、豊富なサンプルコードとともに分かりやすく解説します。
目次
- 1 Python制御構文とは?プログラムの流れを制御する
- 2 【条件分岐編】if文・elif文・else文の使い方
- 3 【繰り返し処理編】for文とwhile文の使い方
- 4 【ループ制御編】break・continue・else節
- 5 【ネストと応用編】入れ子構造と実践的な使用例
- 6 【例外処理編】try・except・finally文
- 7 【その他の制御構文編】pass・with・assert文
- 8 【実践編】実用的な制御構文の使用例
- 9 【パフォーマンス編】効率的な制御構文の書き方
- 10 【デバッグ編】制御構文のデバッグテクニック
- 11 よくある間違いと対処法
- 12 まとめ:Python制御構文をマスターしよう
- 13 ■らくらくPython塾 – 読むだけでマスター
Python制御構文とは?プログラムの流れを制御する
制御構文とは、プログラムの実行順序や処理の繰り返しを制御するための文法です。Pythonの主要な制御構文は以下の通りです。
Python制御構文の種類
- 条件分岐: if文、elif文、else文
- 繰り返し処理: for文、while文
- ループ制御: break文、continue文、else節
- 例外処理: try文、except文、finally文
- その他: pass文、with文
【条件分岐編】if文・elif文・else文の使い方
1. 基本的なif文
score = 85
if score >= 80:
print("合格です")
# 複数条件の場合
if score >= 90:
print("優秀")
elif score >= 70:
print("良好")
else:
print("要努力")
2. 比較演算子と論理演算子
age = 25
income = 400
# 比較演算子
if age >= 20:
print("成人です")
# 論理演算子(and, or, not)
if age >= 20 and income >= 300:
print("ローン審査通過")
if age < 18 or income < 200:
print("条件未達")
if not (age < 18):
print("18歳以上")
3. in演算子とis演算子
fruits = ["apple", "banana", "orange"]
user_input = "apple"
# in演算子
if user_input in fruits:
print("果物です")
# is演算子(同一オブジェクト判定)
value = None
if value is None:
print("値が設定されていません")
# is not
if user_input is not None:
print("値が存在します")
4. 三項演算子(条件式)
# 基本的な三項演算子
age = 17
status = "成人" if age >= 18 else "未成年"
print(status)
# 関数内での使用
def get_discount(is_member):
return 0.1 if is_member else 0.0
discount = get_discount(True)
【繰り返し処理編】for文とwhile文の使い方
1. 基本的なfor文
# リストの反復
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(f"数値: {num}")
# 文字列の反復
for char in "Python":
print(char)
# 辞書の反復
person = {"名前": "田中", "年齢": 30}
for key, value in person.items():
print(f"{key}: {value}")
2. range関数を使ったfor文
# 基本的なrange
for i in range(5): # 0から4まで
print(i)
# 開始値と終了値を指定
for i in range(1, 6): # 1から5まで
print(i)
# ステップを指定
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# 逆順
for i in range(5, 0, -1): # 5, 4, 3, 2, 1
print(i)
3. enumerate関数でインデックス取得
fruits = ["apple", "banana", "orange"]
# インデックス付きで反復
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 開始インデックスを指定
for index, fruit in enumerate(fruits, 1):
print(f"{index}番目: {fruit}")
4. zip関数で複数リストの同時処理
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["Tokyo", "Osaka", "Kyoto"]
for name, age, city in zip(names, ages, cities):
print(f"{name}さん({age}歳)は{city}在住")
5. while文の基本的な使い方
# 基本的なwhile文
count = 0
while count < 5:
print(f"カウント: {count}")
count += 1
# 条件を満たすまで入力を求める
while True:
user_input = input("'quit'を入力すると終了: ")
if user_input == "quit":
break
print(f"入力値: {user_input}")
【ループ制御編】break・continue・else節
1. break文でループから脱出
# for文でのbreak
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4が出力
# while文でのbreak
count = 0
while True:
if count >= 3:
break
print(f"実行回数: {count}")
count += 1
2. continue文で次の反復へ
# 偶数のみ処理をスキップ
for i in range(10):
if i % 2 == 0:
continue
print(f"奇数: {i}") # 1, 3, 5, 7, 9が出力
# リストから条件に合う要素のみ処理
numbers = [1, -2, 3, -4, 5]
for num in numbers:
if num < 0:
continue
print(f"正の数: {num}")
3. else節の使用
# forのelse節(break無しで完了時に実行)
for i in range(5):
if i == 10: # この条件は満たされない
break
print(i)
else:
print("ループが正常に完了しました")
# whileのelse節
count = 0
while count < 3:
print(count)
count += 1
else:
print("whileループが完了しました")
【ネストと応用編】入れ子構造と実践的な使用例
1. ネストしたif文
age = 25
has_license = True
has_car = False
if age >= 18:
if has_license:
if has_car:
print("運転できます")
else:
print("車が必要です")
else:
print("免許が必要です")
else:
print("年齢が足りません")
2. ネストしたループ
# 九九表の作成
for i in range(1, 4): # 1から3まで
for j in range(1, 4): # 1から3まで
print(f"{i} × {j} = {i * j}")
print("---") # 区切り線
# 2次元リストの処理
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print() # 改行
3. リスト内包表記
# 基本的なリスト内包表記
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares) # [1, 4, 9, 16, 25]
# 条件付きリスト内包表記
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares) # [4, 16]
# ネストしたリスト内包表記
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
4. 辞書内包表記とセット内包表記
# 辞書内包表記
numbers = [1, 2, 3, 4, 5]
square_dict = {x: x ** 2 for x in numbers}
print(square_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# セット内包表記
text = "hello world"
unique_chars = {char for char in text if char != ' '}
print(unique_chars) # {'h', 'e', 'l', 'o', 'w', 'r', 'd'}
【例外処理編】try・except・finally文
1. 基本的な例外処理
try:
number = int(input("数値を入力: "))
result = 10 / number
print(f"結果: {result}")
except ValueError:
print("無効な数値です")
except ZeroDivisionError:
print("0で割ることはできません")
2. 複数例外の処理とfinally節
try:
file = open("data.txt", "r")
data = file.read()
print(data)
except (FileNotFoundError, PermissionError) as e:
print(f"ファイルエラー: {e}")
except Exception as e:
print(f"予期しないエラー: {e}")
finally:
print("処理が完了しました")
3. else節とカスタム例外
class CustomError(Exception):
pass
try:
value = int(input("1-10の数値を入力: "))
if value < 1 or value > 10:
raise CustomError("範囲外の値です")
except ValueError:
print("数値を入力してください")
except CustomError as e:
print(f"カスタムエラー: {e}")
else:
print(f"正常な値: {value}")
【その他の制御構文編】pass・with・assert文
1. pass文(何もしない)
# 関数の雛形作成
def future_function():
pass # 後で実装予定
# 条件分岐で何もしない場合
score = 85
if score >= 90:
print("優秀")
elif score >= 70:
pass # 特に処理なし
else:
print("要努力")
2. with文(コンテキストマネージャー)
# ファイル操作
with open("data.txt", "w") as file:
file.write("Hello, World!")
# ファイルは自動的に閉じられる
# 複数ファイルの同時処理
with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
data = infile.read()
outfile.write(data.upper())
3. assert文(デバッグ用)
def divide(a, b):
assert b != 0, "0で割ることはできません"
return a / b
# 正常な場合
result = divide(10, 2) # 5.0
# エラーが発生する場合
# result = divide(10, 0) # AssertionError
【実践編】実用的な制御構文の使用例
1. 入力値検証システム
def validate_user_input():
while True:
try:
age = int(input("年齢を入力(0-120): "))
if 0 <= age <= 120:
return age
else:
print("0-120の範囲で入力してください")
except ValueError:
print("数値を入力してください")
user_age = validate_user_input()
print(f"入力された年齢: {user_age}")
2. メニュー選択システム
def show_menu():
print("\n=== メニュー ===")
print("1. データ表示")
print("2. データ追加")
print("3. データ削除")
print("0. 終了")
def main():
while True:
show_menu()
choice = input("選択してください: ")
if choice == "1":
print("データを表示します")
elif choice == "2":
print("データを追加します")
elif choice == "3":
print("データを削除します")
elif choice == "0":
print("プログラムを終了します")
break
else:
print("無効な選択です")
main()
3. データ処理パイプライン
def process_data(numbers):
# フィルタリング:正の数のみ
positive_numbers = [n for n in numbers if n > 0]
# 変換:平方根を計算
import math
sqrt_numbers = []
for num in positive_numbers:
try:
sqrt_val = math.sqrt(num)
sqrt_numbers.append(sqrt_val)
except ValueError:
continue
# 集約:合計と平均
if sqrt_numbers:
total = sum(sqrt_numbers)
average = total / len(sqrt_numbers)
return {"合計": total, "平均": average, "件数": len(sqrt_numbers)}
else:
return {"エラー": "有効なデータがありません"}
# 使用例
data = [1, -2, 4, 9, -5, 16]
result = process_data(data)
print(result)
4. ログ解析システム
def analyze_log(log_lines):
stats = {"INFO": 0, "WARNING": 0, "ERROR": 0}
errors = []
for line_num, line in enumerate(log_lines, 1):
line = line.strip()
if not line:
continue
# ログレベルの判定
if "INFO" in line:
stats["INFO"] += 1
elif "WARNING" in line:
stats["WARNING"] += 1
elif "ERROR" in line:
stats["ERROR"] += 1
errors.append(f"行{line_num}: {line}")
return stats, errors
# サンプルログ
sample_logs = [
"2025-01-15 INFO: システム開始",
"2025-01-15 WARNING: メモリ使用率が高い",
"2025-01-15 ERROR: データベース接続失敗",
"",
"2025-01-15 INFO: 処理完了"
]
stats, error_list = analyze_log(sample_logs)
print(f"統計: {stats}")
print(f"エラー一覧: {error_list}")
【パフォーマンス編】効率的な制御構文の書き方
1. 早期リターンパターン
# ❌ 悪い例:ネストが深い
def process_user(user):
if user is not None:
if user.is_active:
if user.age >= 18:
return f"処理実行: {user.name}"
else:
return "年齢不足"
else:
return "非アクティブユーザー"
else:
return "ユーザーが存在しません"
# ✅ 良い例:早期リターン
def process_user_better(user):
if user is None:
return "ユーザーが存在しません"
if not user.is_active:
return "非アクティブユーザー"
if user.age < 18:
return "年齢不足"
return f"処理実行: {user.name}"
2. ループの最適化
# ❌ 悪い例:毎回関数を呼び出し
numbers = list(range(1000))
result = []
for num in numbers:
if len(str(num)) == 3: # 毎回len()とstr()を呼び出し
result.append(num)
# ✅ 良い例:条件を先に計算
numbers = list(range(1000))
result = [num for num in numbers if 100 <= num <= 999]
3. 辞書を使った条件分岐の最適化
# ❌ 悪い例:長いif-elif文
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# ✅ 良い例:辞書とリスト内包表記
def get_grade_better(score):
grade_ranges = [(90, "A"), (80, "B"), (70, "C"), (60, "D")]
for threshold, grade in grade_ranges:
if score >= threshold:
return grade
return "F"
【デバッグ編】制御構文のデバッグテクニック
1. ログを使った流れの確認
import logging
logging.basicConfig(level=logging.DEBUG)
def debug_example(numbers):
logging.debug(f"処理開始: {numbers}")
for i, num in enumerate(numbers):
logging.debug(f"処理中 {i}: {num}")
if num < 0:
logging.warning(f"負の数をスキップ: {num}")
continue
if num > 100:
logging.info(f"大きな数値で処理終了: {num}")
break
result = num * 2
logging.debug(f"結果: {result}")
logging.debug("処理完了")
debug_example([5, -3, 10, 150, 20])
2. アサーションを使った状態確認
def safe_process_list(items):
assert isinstance(items, list), "引数はリストである必要があります"
assert len(items) > 0, "空のリストは処理できません"
processed = []
for item in items:
assert isinstance(item, (int, float)), f"数値以外が含まれています: {item}"
if item > 0:
processed.append(item * 2)
assert len(processed) > 0, "処理できるアイテムがありませんでした"
return processed
よくある間違いと対処法
1. 無限ループの回避
# ❌ 危険:無限ループの可能性
count = 0
while count < 10:
print(count)
# count += 1 を忘れがち
# ✅ 安全:カウンターを必ず更新
count = 0
max_iterations = 1000 # 安全弁
while count < 10 and max_iterations > 0:
print(count)
count += 1
max_iterations -= 1
2. 変数スコープの理解
# 注意:ループ変数のスコープ
for i in range(3):
x = i * 2
print(f"ループ後のi: {i}") # i=2(最後の値)
print(f"ループ後のx: {x}") # x=4(最後の値)
# 関数内でのスコープ
def scope_example():
for i in range(3):
local_var = i
# local_varはここでも使用可能
return local_var
result = scope_example() # 2が返される
まとめ:Python制御構文をマスターしよう
Python制御構文は、プログラムの基本的な流れを制御する重要な文法です。この記事で紹介した基本的な使い方から実践的なテクニックまでを段階的に習得することで、より効率的で読みやすいPythonコードを書けるようになります。
重要なポイント:
- 適切な制御構文の選択: 目的に応じてif文、for文、while文を使い分け
- 可読性の重視: ネストを浅くし、早期リターンを活用
- 例外処理の実装: try-except文でエラーハンドリングを適切に実装
- パフォーマンスの考慮: リスト内包表記や適切なデータ構造を活用
まずは基本的なif文とfor文から始めて、徐々にwhile文や例外処理などの高度な機能を取り入れてみてください。制御構文をマスターすることで、より柔軟で効率的なPythonプログラムを開発できるようになります。
この記事がお役に立ちましたら、ぜひシェアしてください。Python制御構文やプログラミング基礎に関するご質問がございましたら、お気軽にコメントでお知らせください。
■らくらくPython塾 – 読むだけでマスター
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座




