0
0

Pythonのfor文の使い方を解説

Posted at

Pythonのfor文の使い方を解説

Pythonのfor文は、リスト、タプル、文字列、辞書などの反復可能な(iterable)オブジェクト内の要素を反復処理するために使用されます。以下にPythonのfor文の基本的な使い方を説明します。

リストを反復処理する例

fruits = ["りんご", "バナナ", "オレンジ"]

for fruit in fruits:
    print(fruit)

リスト fruits 内の各要素を順番に取り出し、それを変数 fruit に代入してループ内で使用します。ループごとに果物が表示されます。

範囲(range)を使用する例

for i in range(5):
    print(i)

このコードは、0から4までの数字を表示します。range(5) は0から4までの範囲を生成し、for ループでそれらの数字を反復処理します。

文字列を反復処理する例

text = "Hello, World!"

for char in text:
    print(char)

このコードは文字列 text 内の各文字を順番に取り出し、それを変数 char に代入して表示します。

辞書を反復処理する例

student_scores = {"Alice": 95, "Bob": 87, "Charlie": 91}

for student, score in student_scores.items():
    print(f"{student}: {score}")

このコードは辞書 student_scores 内のキーと値のペアを順番に取り出し、それぞれを変数 student と score に代入して表示します。items() メソッドを使用して辞書のキーと値を取得します。

これらはPythonのfor文の基本的な使い方です。for文は反復処理が必要な場合に非常に便利で、さまざまなデータ構造を処理するのに役立ちます。

Pythonのお役立ち情報

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0