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
  • 對於 sequence 中每個 value,執行此 action

    • 由於前一行有冒號,action 需縮排
  • sequence = 可疊代物件,如 list、dictionary 等

  • 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 入門(開發者向)

迭代字典(dictionary)

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 = key(食材名稱)
  • qty = value(數量)
Python 入門(開發者向)

迭代字典(dictionary)

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 入門(開發者向)

迭代字典(dictionary)

# 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

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...