for ループ

開発者のためのPython入門

Jasmin Ludolf

Senior Data Science Content Developer

個別比較

# Ingredient quantities
quantities = [500, 400, 15, 20, 30, 5]
# Validate values
quantities[0] < 10
False
quantities[1] < 10
False
開発者のためのPython入門

forループの構文

for value in sequence:
    action
  • for で指定されるように、sequence の各 value に対して actionを実行する

    • 前の行にコロンがあるためactionはインデントされる
  • sequence = イテラブル(リスト、辞書など)

  • value = イテレータ(インデックス)
    • 任意の名前が可能なプレースホルダーであり、iという表記が一般的
開発者のためのPython入門

個々の値を出力する

# Ingredients list
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]


# Loop through and print each ingredient for ingredient in ingredients:
print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
開発者のためのPython入門

forループ内の条件文

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:
開発者のためのPython入門

forループ内の条件文

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

# Check if quantity is more than 500 if qty > 500: print("Plenty in stock") elif qty >= 100: print("Enough for a small portion") else: print("Nearly out!")
開発者のためのPython入門

forループ内の条件文

Plenty in stock
Enough for small
Nearly out!
Nearly out!
Nearly out!
開発者のためのPython入門

文字列をループ処理する

ingredient_name = "pasta"

# Loop through each character for letter in ingredient_name: print(letter)
p
a
s
t
a
  • テキストの検証や特殊文字の確認に役立つ
開発者のためのPython入門

辞書をループ処理する

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# Loop through keys and values for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
  • item = キー(材料名)
  • qty = 値(数量)
開発者のためのPython入門

辞書をループ処理する

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2

# Calculate scaled quantities for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
開発者のためのPython入門

辞書をループ処理する

# Loop through keys only
for item in ingredients.keys():
    print(item)
pasta
tomatoes
garlic
# Loop through values only
for qty in ingredients.values():
    print(qty, "grams")
500 grams
400 grams
30 grams
開発者のためのPython入門

範囲

range(start, end + 1)
  • start = 開始番号
  • end = 終了番号
  • 値の生成または変更に使用される
for i in range(1, 6):
    print(i)
1
2
3
4
5
開発者のためのPython入門

練習しましょう!

開発者のためのPython入門

Preparing Video For Download...