For loops

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 loop

for value in sequence:
    action
  • for แต่ละ value ใน sequence ให้ดำเนิน action

    • action เยื้องเข้าเพราะมีเครื่องหมาย colon ในบรรทัดก่อนหน้า
  • sequence = iterable เช่น list, dictionary เป็นต้น

  • value = iterator คือ index
    • เป็น placeholder (ตั้งชื่อใดก็ได้) นิยมใช้ 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 loop

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

for qty in quantities:
Python เบื้องต้นสำหรับนักพัฒนา

คำสั่งเงื่อนไขใน for loop

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 loop

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