while文 - 条件が満たされるまで繰り返す
目次
このレッスンで学ぶこと
- while文とは何か
- while文の基本構文
- for文との違い
- while文の実用例と注意点
while文とは
while文は、指定された条件が真(True)である限り、処理を繰り返し実行する制御構文です。繰り返し回数が事前にわからない場合や、特定の条件が満たされるまで処理を続けたい場合に使用されます。
while文の基本構造
Pythonwhile 条件式: 繰り返す処理 # 条件が真の間、実行される
while文の構成要素
| 要素 | 説明 | 例 |
|---|---|---|
while | ループのキーワード | 必須 |
| 条件式 | 繰り返すかどうかを判定 | count < 5, flag == True |
: | ブロックの開始 | 必須 |
| インデント | ループの処理の範囲 | 4文字スペース |
| 処理 | 繰り返す内容 | count += 1 など |
while文の特徴
- 条件が真である限り無限に繰り返す可能性がある
- 条件式を更新する処理が必須(無限ループを避けるため)
- 繰り返し回数が不定の場合に適している
- ユーザー入力や外部条件に基づいた制御に便利
簡単な例
Python# 0から4まで表示 count = 0 while count < 5: print(count) count += 1 # 実行結果: # 0 # 1 # 2 # 3 # 4 # パスワードが正しいまで繰り返す password = "" while password != "1234": password = input("パスワード: ") print("ログイン成功!")
なぜwhile文が必要なのか?
for文は「決まった回数」繰り返すのに便利ですが、「条件が満たされるまで」繰り返したい場合はwhile文が適しています。
Python# ユーザーが正しい値を入力するまで繰り返す password = "" while password != "1234": password = input("パスワードを入力してください: ") print("ログイン成功!")
while文を使うことで、条件次第で繰り返し回数が変わる処理を書けます。
💡 豆知識: while文の「while」は英語で「〜の間」という意味です。「条件が真の間、処理を繰り返す」という動作を表しています。
while文の基本構文
構文
機能: 条件式が真の間、処理を繰り返し実行します。
書き方:
Pythonwhile 条件式: 繰り返す処理
用途: 回数が事前にわからない繰り返し、条件達成まで継続、ユーザー入力の待機
注意点:
- 条件式が偽にならないと無限ループになる
- コロン(:)とインデントが必須
- 条件式を変化させる処理が必要
Python# 基本的な使い方 count = 0 while count < 5: print(f"カウント: {count}") count += 1 print("終了")
実行結果:
カウント: 0
カウント: 1
カウント: 2
カウント: 3
カウント: 4
終了
for文との違い
for文とwhile文の比較
Python# for文: 回数が決まっている print("=== for文 ===") for i in range(5): print(i) # while文: 条件で制御 print("\n=== while文 ===") i = 0 while i < 5: print(i) i += 1
実行結果:
=== for文 ===
0
1
2
3
4
=== while文 ===
0
1
2
3
4
使い分けのポイント:
- for文: 繰り返し回数が明確な場合
- while文: 条件次第で回数が変わる場合
while文の基本パターン
パターン1: カウンタ変数を使う
Python# 10から0までカウントダウン count = 10 while count >= 0: print(count) count -= 1 print("発射!")
実行結果:
10
9
8
7
6
5
4
3
2
1
0
発射!
パターン2: フラグ変数を使う
機能: ブール変数で繰り返しを制御します。
書き方:
Pythonflag = True while flag: # 処理 if 条件: flag = False
用途: 複雑な終了条件、複数箇所からの制御
注意点: フラグの更新を忘れると無限ループになる
Python# ユーザーが"quit"を入力するまで継続 running = True while running: command = input("コマンドを入力してください (quit で終了): ") if command == "quit": running = False else: print(f"入力されたコマンド: {command}") print("プログラムを終了します")
パターン3: 無限ループ + break
Python# 無限ループから条件でbreak while True: number = input("数値を入力してください (0で終了): ") if number == "0": break print(f"入力された数値: {number}") print("終了しました")
具体例
例1: 合計が100を超えるまで
Pythontotal = 0 count = 1 while total < 100: total += count print(f"{count}を加算: 合計 = {total}") count += 1 print(f"\n{count - 1}回で100を超えました")
実行結果:
1を加算: 合計 = 1
2を加算: 合計 = 3
3を加算: 合計 = 6
4を加算: 合計 = 10
5を加算: 合計 = 15
...
13を加算: 合計 = 91
14を加算: 合計 = 105
14回で100を超えました
例2: パスワード認証
Pythoncorrect_password = "python123" attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input("パスワードを入力してください: ") attempts += 1 if password == correct_password: print("ログイン成功!") break else: remaining = max_attempts - attempts if remaining > 0: print(f"パスワードが違います。残り{remaining}回") else: print("ログイン失敗。アカウントがロックされました。")
例3: 数当てゲーム
Pythonimport random answer = random.randint(1, 100) attempts = 0 print("=== 数当てゲーム ===") print("1〜100の数を当ててください") while True: guess = int(input("予想: ")) attempts += 1 if guess == answer: print(f"正解! {attempts}回で当たりました") break elif guess < answer: print("もっと大きい数です") else: print("もっと小さい数です")
例4: 入力値の検証
Python# 1〜10の範囲の数値が入力されるまで繰り返す while True: value = int(input("1〜10の数値を入力してください: ")) if 1 <= value <= 10: print(f"{value}が入力されました") break else: print("範囲外です。もう一度入力してください")
例5: リストが空になるまで処理
Pythontasks = ["メール確認", "資料作成", "会議準備"] print("=== タスク処理 ===") while tasks: # リストが空でない間 task = tasks.pop(0) print(f"処理中: {task}") print("すべてのタスクが完了しました")
実行結果:
=== タスク処理 ===
処理中: メール確認
処理中: 資料作成
処理中: 会議準備
すべてのタスクが完了しました
例6: 残高管理
Pythonbalance = 10000 print("=== ATMシミュレーション ===") print(f"残高: {balance}円") while balance > 0: withdrawal = int(input("引き出し額を入力してください (0で終了): ")) if withdrawal == 0: break if withdrawal > balance: print(f"残高不足です(残高: {balance}円)") else: balance -= withdrawal print(f"{withdrawal}円を引き出しました(残高: {balance}円)") print(f"最終残高: {balance}円")
無限ループに注意
無限ループの例
Python# 危険: 条件が常に真 count = 0 while count < 5: print(count) # count += 1 を忘れている! # これは無限ループになる
無限ループの回避方法
Python# 方法1: カウンタを確実に更新 count = 0 while count < 5: print(count) count += 1 # 必ず更新 # 方法2: 最大繰り返し回数を設定 count = 0 max_iterations = 1000 while count < 5 and max_iterations > 0: print(count) count += 1 max_iterations -= 1 # 方法3: breakで確実に抜ける count = 0 while True: if count >= 5: break print(count) count += 1
よくある間違い
間違い1: 条件式が変化しない
Python# 間違い: 無限ループ x = 10 while x > 0: print(x) # x を減らすのを忘れている # 正しい x = 10 while x > 0: print(x) x -= 1
間違い2: 条件式の誤り
Python# 間違い: 1回も実行されない count = 0 while count > 5: # 最初から偽 print(count) count += 1 # 正しい count = 0 while count < 5: print(count) count += 1
間違い3: インデントの誤り
Python# 間違い count = 0 while count < 5: print(count) count += 1 # ループの外で実行される(無限ループ) # 正しい count = 0 while count < 5: print(count) count += 1 # ループの中で実行される
間違い4: 型の不一致
Python# 間違い: 文字列と数値の比較 count = "0" while count < 5: # エラーまたは予期しない動作 print(count) count += 1 # 正しい count = 0 while count < 5: print(count) count += 1
間違い5: 空のコレクションチェック
Python# 間違い: 長さをチェックしている items = [1, 2, 3] while len(items) > 0: print(items.pop()) # よりPythonic items = [1, 2, 3] while items: # 空でない間 print(items.pop())
練習問題
問題1(基礎)⭐☆☆
1から10までの数値を表示するプログラムをwhile文で書いてください。
💡 ヒント
カウンタ変数を1から始めて、10以下の間繰り返します。
✅ 解答例
Pythoncount = 1 while count <= 10: print(count) count += 1
実行結果:
1
2
3
4
5
6
7
8
9
10
解説: count を1から始めて、10以下の間繰り返し、毎回1ずつ増やしています。
問題2(基礎)⭐☆☆
10から1までカウントダウンするプログラムを書いてください。
💡 ヒント
count を10から始めて、1以上の間繰り返し、毎回1ずつ減らします。
✅ 解答例
Pythoncount = 10 while count >= 1: print(count) count -= 1 print("発射!")
実行結果:
10
9
8
7
6
5
4
3
2
1
発射!
解説: count を減らしながら1まで表示しています。
問題3(応用)⭐⭐☆
1から順に足していき、合計が50を超えたら終了するプログラムを書いてください。
💡 ヒント
合計が50以下の間、数値を足していきます。
✅ 解答例
Pythontotal = 0 count = 1 while total <= 50: total += count print(f"{count}を加算: 合計 = {total}") count += 1 print(f"\n合計が50を超えました")
実行結果:
1を加算: 合計 = 1
2を加算: 合計 = 3
3を加算: 合計 = 6
4を加算: 合計 = 10
5を加算: 合計 = 15
6を加算: 合計 = 21
7を加算: 合計 = 28
8を加算: 合計 = 36
9を加算: 合計 = 45
10を加算: 合計 = 55
合計が50を超えました
解説: 合計が50以下の間、順番に数値を加算しています。
まとめ
このレッスンでは、while文で条件ベースの繰り返しを行う方法を学びました。
- while文は、条件が真である間だけ処理を繰り返す構文です。
- 反復のたびに条件に関わる値を更新することが重要です。
- 終了条件を明確にしないと無限ループになるリスクがあります。
- 回数が未確定な処理や入力待ち処理でwhile文が有効です。
- ループ変数の変化を確認しながら実装すると安全です。
while文 - 条件が満たされるまで繰り返す
目次
このレッスンで学ぶこと
- while文とは何か
- while文の基本構文
- for文との違い
- while文の実用例と注意点
while文とは
while文は、指定された条件が真(True)である限り、処理を繰り返し実行する制御構文です。繰り返し回数が事前にわからない場合や、特定の条件が満たされるまで処理を続けたい場合に使用されます。
while文の基本構造
Pythonwhile 条件式: 繰り返す処理 # 条件が真の間、実行される
while文の構成要素
| 要素 | 説明 | 例 |
|---|---|---|
while | ループのキーワード | 必須 |
| 条件式 | 繰り返すかどうかを判定 | count < 5, flag == True |
: | ブロックの開始 | 必須 |
| インデント | ループの処理の範囲 | 4文字スペース |
| 処理 | 繰り返す内容 | count += 1 など |
while文の特徴
- 条件が真である限り無限に繰り返す可能性がある
- 条件式を更新する処理が必須(無限ループを避けるため)
- 繰り返し回数が不定の場合に適している
- ユーザー入力や外部条件に基づいた制御に便利
簡単な例
Python# 0から4まで表示 count = 0 while count < 5: print(count) count += 1 # 実行結果: # 0 # 1 # 2 # 3 # 4 # パスワードが正しいまで繰り返す password = "" while password != "1234": password = input("パスワード: ") print("ログイン成功!")
なぜwhile文が必要なのか?
for文は「決まった回数」繰り返すのに便利ですが、「条件が満たされるまで」繰り返したい場合はwhile文が適しています。
Python# ユーザーが正しい値を入力するまで繰り返す password = "" while password != "1234": password = input("パスワードを入力してください: ") print("ログイン成功!")
while文を使うことで、条件次第で繰り返し回数が変わる処理を書けます。
💡 豆知識: while文の「while」は英語で「〜の間」という意味です。「条件が真の間、処理を繰り返す」という動作を表しています。
while文の基本構文
構文
機能: 条件式が真の間、処理を繰り返し実行します。
書き方:
Pythonwhile 条件式: 繰り返す処理
用途: 回数が事前にわからない繰り返し、条件達成まで継続、ユーザー入力の待機
注意点:
- 条件式が偽にならないと無限ループになる
- コロン(:)とインデントが必須
- 条件式を変化させる処理が必要
Python# 基本的な使い方 count = 0 while count < 5: print(f"カウント: {count}") count += 1 print("終了")
実行結果:
カウント: 0
カウント: 1
カウント: 2
カウント: 3
カウント: 4
終了
for文との違い
for文とwhile文の比較
Python# for文: 回数が決まっている print("=== for文 ===") for i in range(5): print(i) # while文: 条件で制御 print("\n=== while文 ===") i = 0 while i < 5: print(i) i += 1
実行結果:
=== for文 ===
0
1
2
3
4
=== while文 ===
0
1
2
3
4
使い分けのポイント:
- for文: 繰り返し回数が明確な場合
- while文: 条件次第で回数が変わる場合
while文の基本パターン
パターン1: カウンタ変数を使う
Python# 10から0までカウントダウン count = 10 while count >= 0: print(count) count -= 1 print("発射!")
実行結果:
10
9
8
7
6
5
4
3
2
1
0
発射!
パターン2: フラグ変数を使う
機能: ブール変数で繰り返しを制御します。
書き方:
Pythonflag = True while flag: # 処理 if 条件: flag = False
用途: 複雑な終了条件、複数箇所からの制御
注意点: フラグの更新を忘れると無限ループになる
Python# ユーザーが"quit"を入力するまで継続 running = True while running: command = input("コマンドを入力してください (quit で終了): ") if command == "quit": running = False else: print(f"入力されたコマンド: {command}") print("プログラムを終了します")
パターン3: 無限ループ + break
Python# 無限ループから条件でbreak while True: number = input("数値を入力してください (0で終了): ") if number == "0": break print(f"入力された数値: {number}") print("終了しました")
具体例
例1: 合計が100を超えるまで
Pythontotal = 0 count = 1 while total < 100: total += count print(f"{count}を加算: 合計 = {total}") count += 1 print(f"\n{count - 1}回で100を超えました")
実行結果:
1を加算: 合計 = 1
2を加算: 合計 = 3
3を加算: 合計 = 6
4を加算: 合計 = 10
5を加算: 合計 = 15
...
13を加算: 合計 = 91
14を加算: 合計 = 105
14回で100を超えました
例2: パスワード認証
Pythoncorrect_password = "python123" attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input("パスワードを入力してください: ") attempts += 1 if password == correct_password: print("ログイン成功!") break else: remaining = max_attempts - attempts if remaining > 0: print(f"パスワードが違います。残り{remaining}回") else: print("ログイン失敗。アカウントがロックされました。")
例3: 数当てゲーム
Pythonimport random answer = random.randint(1, 100) attempts = 0 print("=== 数当てゲーム ===") print("1〜100の数を当ててください") while True: guess = int(input("予想: ")) attempts += 1 if guess == answer: print(f"正解! {attempts}回で当たりました") break elif guess < answer: print("もっと大きい数です") else: print("もっと小さい数です")
例4: 入力値の検証
Python# 1〜10の範囲の数値が入力されるまで繰り返す while True: value = int(input("1〜10の数値を入力してください: ")) if 1 <= value <= 10: print(f"{value}が入力されました") break else: print("範囲外です。もう一度入力してください")
例5: リストが空になるまで処理
Pythontasks = ["メール確認", "資料作成", "会議準備"] print("=== タスク処理 ===") while tasks: # リストが空でない間 task = tasks.pop(0) print(f"処理中: {task}") print("すべてのタスクが完了しました")
実行結果:
=== タスク処理 ===
処理中: メール確認
処理中: 資料作成
処理中: 会議準備
すべてのタスクが完了しました
例6: 残高管理
Pythonbalance = 10000 print("=== ATMシミュレーション ===") print(f"残高: {balance}円") while balance > 0: withdrawal = int(input("引き出し額を入力してください (0で終了): ")) if withdrawal == 0: break if withdrawal > balance: print(f"残高不足です(残高: {balance}円)") else: balance -= withdrawal print(f"{withdrawal}円を引き出しました(残高: {balance}円)") print(f"最終残高: {balance}円")
無限ループに注意
無限ループの例
Python# 危険: 条件が常に真 count = 0 while count < 5: print(count) # count += 1 を忘れている! # これは無限ループになる
無限ループの回避方法
Python# 方法1: カウンタを確実に更新 count = 0 while count < 5: print(count) count += 1 # 必ず更新 # 方法2: 最大繰り返し回数を設定 count = 0 max_iterations = 1000 while count < 5 and max_iterations > 0: print(count) count += 1 max_iterations -= 1 # 方法3: breakで確実に抜ける count = 0 while True: if count >= 5: break print(count) count += 1
よくある間違い
間違い1: 条件式が変化しない
Python# 間違い: 無限ループ x = 10 while x > 0: print(x) # x を減らすのを忘れている # 正しい x = 10 while x > 0: print(x) x -= 1
間違い2: 条件式の誤り
Python# 間違い: 1回も実行されない count = 0 while count > 5: # 最初から偽 print(count) count += 1 # 正しい count = 0 while count < 5: print(count) count += 1
間違い3: インデントの誤り
Python# 間違い count = 0 while count < 5: print(count) count += 1 # ループの外で実行される(無限ループ) # 正しい count = 0 while count < 5: print(count) count += 1 # ループの中で実行される
間違い4: 型の不一致
Python# 間違い: 文字列と数値の比較 count = "0" while count < 5: # エラーまたは予期しない動作 print(count) count += 1 # 正しい count = 0 while count < 5: print(count) count += 1
間違い5: 空のコレクションチェック
Python# 間違い: 長さをチェックしている items = [1, 2, 3] while len(items) > 0: print(items.pop()) # よりPythonic items = [1, 2, 3] while items: # 空でない間 print(items.pop())
練習問題
問題1(基礎)⭐☆☆
1から10までの数値を表示するプログラムをwhile文で書いてください。
💡 ヒント
カウンタ変数を1から始めて、10以下の間繰り返します。
✅ 解答例
Pythoncount = 1 while count <= 10: print(count) count += 1
実行結果:
1
2
3
4
5
6
7
8
9
10
解説: count を1から始めて、10以下の間繰り返し、毎回1ずつ増やしています。
問題2(基礎)⭐☆☆
10から1までカウントダウンするプログラムを書いてください。
💡 ヒント
count を10から始めて、1以上の間繰り返し、毎回1ずつ減らします。
✅ 解答例
Pythoncount = 10 while count >= 1: print(count) count -= 1 print("発射!")
実行結果:
10
9
8
7
6
5
4
3
2
1
発射!
解説: count を減らしながら1まで表示しています。
問題3(応用)⭐⭐☆
1から順に足していき、合計が50を超えたら終了するプログラムを書いてください。
💡 ヒント
合計が50以下の間、数値を足していきます。
✅ 解答例
Pythontotal = 0 count = 1 while total <= 50: total += count print(f"{count}を加算: 合計 = {total}") count += 1 print(f"\n合計が50を超えました")
実行結果:
1を加算: 合計 = 1
2を加算: 合計 = 3
3を加算: 合計 = 6
4を加算: 合計 = 10
5を加算: 合計 = 15
6を加算: 合計 = 21
7を加算: 合計 = 28
8を加算: 合計 = 36
9を加算: 合計 = 45
10を加算: 合計 = 55
合計が50を超えました
解説: 合計が50以下の間、順番に数値を加算しています。
まとめ
このレッスンでは、while文で条件ベースの繰り返しを行う方法を学びました。
- while文は、条件が真である間だけ処理を繰り返す構文です。
- 反復のたびに条件に関わる値を更新することが重要です。
- 終了条件を明確にしないと無限ループになるリスクがあります。
- 回数が未確定な処理や入力待ち処理でwhile文が有効です。
- ループ変数の変化を確認しながら実装すると安全です。