メインコンテンツへスキップ
Lesson1 / 7

for文の基本 - 繰り返し処理

目次

このレッスンで学ぶこと

  • for文とは何か
  • for文の基本構文
  • リストや文字列のループ処理
  • for文の実用例

for文とは

for文は、リストや文字列などのコレクションの各要素に対して、順番に同じ処理を繰り返す制御構文です。

for文の基本構造

Python
for 変数 in コレクション:
    繰り返す処理  # 各要素に対して実行

for文の構成要素

要素説明
forループのキーワードfor i in range(5):
変数各要素を格納する変数i, item, name など
in所属を示すキーワード必須
コレクション繰り返し対象のデータリスト、文字列、range() など
:ブロックの開始必須

for文の特徴

  • コレクションの全要素を自動的に処理
  • 繰り返し回数は要素数で決まる
  • インデックスを意識せずに要素にアクセス
  • Python特有の直感的な書き方

簡単な例

Python
# リストの各要素を処理
fruits = ["りんご", "バナナ", "オレンジ"]
for fruit in fruits:
    print(fruit)

# 実行結果:
# りんご
# バナナ
# オレンジ

なぜfor文が必要なのか?

プログラミングでは、同じ処理を何度も繰り返したいことがよくあります。

Python
# for文を使わない場合
print("1回目")
print("2回目")
print("3回目")
print("4回目")
print("5回目")

# for文を使う場合
for i in range(1, 6):
    print(f"{i}回目")

for文を使うことで、繰り返し処理を簡潔に書くことができます。

💡 豆知識: for文の「for」は英語の「〜のために」ではなく、「〜の間」という意味です。プログラミングでは「各要素について」という意味で使われます。


for文の基本構文

構文

機能: リストなどのコレクションの各要素に対して、順番に処理を実行します。

書き方:

Python
for 変数 in コレクション:
    繰り返す処理

用途: リストの全要素を処理、決まった回数の繰り返し、文字列の各文字を処理

注意点:

  • コロン(:)を忘れない
  • 処理はインデント(字下げ)する
  • 変数名は任意(慣習的にiやitemを使う)
Python
# 基本的な使い方
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

実行結果:

1
2
3
4
5

リストのループ処理

リストの各要素を処理

Python
# 果物のリスト
fruits = ["りんご", "バナナ", "オレンジ"]

for fruit in fruits:
    print(f"好きな果物: {fruit}")

実行結果:

好きな果物: りんご
好きな果物: バナナ
好きな果物: オレンジ

数値リストの計算

Python
# 点数のリスト
scores = [85, 92, 78, 95, 88]

# 各点数を表示
for score in scores:
    print(f"点数: {score}点")

# 合計を計算
total = 0
for score in scores:
    total += score

print(f"合計: {total}点")
print(f"平均: {total / len(scores)}点")

実行結果:

点数: 85点
点数: 92点
点数: 78点
点数: 95点
点数: 88点
合計: 438点
平均: 87.6点

文字列のループ処理

文字列の各文字を処理

機能: 文字列の各文字に対して順番に処理を実行します。

書き方:

Python
for 文字 in 文字列:
    処理

用途: 文字数カウント、特定文字の検索、文字列の変換

注意点: 文字列は文字のリストとして扱われる

Python
# 文字列をループ
text = "Python"

for char in text:
    print(char)

実行結果:

P
y
t
h
o
n

文字数をカウント

Python
text = "Hello World"
space_count = 0

for char in text:
    if char == " ":
        space_count += 1

print(f"スペースの数: {space_count}個")

実行結果:

スペースの数: 1個

具体例

例1: 買い物リスト

Python
shopping_list = ["牛乳", "パン", "卵", "りんご"]

print("=== 買い物リスト ===")
for item in shopping_list:
    print(f"- {item}")

実行結果:

=== 買い物リスト ===
- 牛乳
- パン
- 卵
- りんご

例2: 成績判定

Python
scores = [85, 92, 78, 95, 88]

print("=== 成績判定 ===")
for score in scores:
    if score >= 80:
        print(f"{score}点: 優秀")
    else:
        print(f"{score}点: がんばりましょう")

実行結果:

=== 成績判定 ===
85点: 優秀
92点: 優秀
78点: がんばりましょう
95点: 優秀
88点: 優秀

例3: 価格計算

Python
prices = [100, 250, 180, 320]

print("=== 価格一覧 ===")
for price in prices:
    tax_included = int(price * 1.1)
    print(f"本体価格: {price}円 → 税込: {tax_included}円")

実行結果:

=== 価格一覧 ===
本体価格: 100円 → 税込: 110円
本体価格: 250円 → 税込: 275円
本体価格: 180円 → 税込: 198円
本体価格: 320円 → 税込: 352円

例4: 九九の計算

Python
number = 5

print(f"=== {number}の段 ===")
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
    result = number * i
    print(f"{number} × {i} = {result}")

実行結果:

=== 5の段 ===
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45

例5: メールアドレスの検証

Python
email = "user@example.com"
has_at = False

for char in email:
    if char == "@":
        has_at = True
        break

if has_at:
    print("有効なメールアドレスです")
else:
    print("無効なメールアドレスです")

実行結果:

有効なメールアドレスです

例6: パスワード強度チェック

Python
password = "MyPass123"
has_digit = False
has_upper = False

for char in password:
    if char.isdigit():
        has_digit = True
    if char.isupper():
        has_upper = True

print(f"数字を含む: {has_digit}")
print(f"大文字を含む: {has_upper}")

if has_digit and has_upper:
    print("強いパスワードです")
else:
    print("パスワードを強化してください")

実行結果:

数字を含む: True
大文字を含む: True
強いパスワードです

よくある間違い

間違い1: インデントを忘れる

Python
# 間違い
numbers = [1, 2, 3]
for number in numbers:
print(number)  # エラー: インデントが必要

# 正しい
numbers = [1, 2, 3]
for number in numbers:
    print(number)

間違い2: コロンを忘れる

Python
# 間違い
for number in [1, 2, 3]
    print(number)  # エラー: コロンがない

# 正しい
for number in [1, 2, 3]:
    print(number)

間違い3: ループ変数を書き換える

Python
# 問題のある例
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    number = number * 2  # これは元のリストを変更しない
    print(number)

print(numbers)  # [1, 2, 3, 4, 5] 変わっていない

# 正しい(新しいリストを作る)
numbers = [1, 2, 3, 4, 5]
doubled = []
for number in numbers:
    doubled.append(number * 2)

print(doubled)  # [2, 4, 6, 8, 10]

間違い4: ループ中にリストを変更

Python
# 危険な例
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        numbers.remove(number)  # ループ中の削除は危険

# 正しい(新しいリストを作る)
numbers = [1, 2, 3, 4, 5]
odd_numbers = []
for number in numbers:
    if number % 2 != 0:
        odd_numbers.append(number)

print(odd_numbers)  # [1, 3, 5]

間違い5: 空のリストでエラー

Python
# 空のリストは問題ない
empty_list = []
for item in empty_list:
    print(item)  # 何も実行されない(エラーにならない)

print("ループ終了")

実行結果:

ループ終了

練習問題

問題1(基礎)⭐☆☆

リスト [10, 20, 30, 40, 50] の各要素を2倍にして表示してください。

💡 ヒント

各要素に対して * 2 をします。

✅ 解答例
Python
numbers = [10, 20, 30, 40, 50]

for number in numbers:
    doubled = number * 2
    print(f"{number} × 2 = {doubled}")

実行結果:

10 × 2 = 20
20 × 2 = 40
30 × 2 = 60
40 × 2 = 80
50 × 2 = 100

解説: 各要素を2倍にして表示しています。


問題2(基礎)⭐☆☆

文字列 "Hello" の各文字を1行ずつ表示してください。

💡 ヒント

文字列もループできます。

✅ 解答例
Python
text = "Hello"

for char in text:
    print(char)

実行結果:

H
e
l
l
o

解説: 文字列は文字のリストとして扱えます。


問題3(応用)⭐⭐☆

リスト [5, 12, 8, 20, 3, 15] の中から10以上の数値だけを表示してください。

💡 ヒント

if文で条件判定します。

✅ 解答例
Python
numbers = [5, 12, 8, 20, 3, 15]

print("10以上の数値:")
for number in numbers:
    if number >= 10:
        print(number)

実行結果:

10以上の数値:
12
20
15

解説: if文で10以上かどうかを判定し、条件に合う数値だけを表示しています。


まとめ

このレッスンでは、for文による繰り返し処理の基本を学びました。

  • for文は、要素を順番に取り出して処理するための構文です。
  • リストや文字列などの反復可能オブジェクトを対象にループできます。
  • ループ変数を使って、各要素に対する処理を明確に記述できます。
  • 繰り返し処理は集計・表示・検索などの基礎になります。
  • まず単純な反復から動作確認し、徐々に処理を追加することが重要です。