Loop (วนซ้ำ) เป็นพื้นฐานการเขียนโปรแกรม Python มี 2 ประเภทหลัก: for และ while
1. For Loop (วนลูปผ่าน Collection)
Basic For Loop
# Syntax
for variable in collection:
statement
# Example
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print("Value is:", i)
# Output:
# Value is: 1
# Value is: 2
# Value is: 3
# Value is: 4
# Value is: 5
For Loop with range()
# range(stop) - 0 ถึง stop-1
for i in range(5):
print(i)
# 0 1 2 3 4
# range(start, stop) - start ถึง stop-1
for i in range(10, 15):
print(i)
# 10 11 12 13 14
# range(start, stop, step)
for i in range(10, 30, 5):
print(i)
# 10 15 20 25
For Loop with Else
for i in range(6):
print(i)
else:
print("Finished looping.")
# 0 1 2 3 4 5
# Finished looping.
# ⚠️ Else ใน For ทำงานเสมอเมื่อลูปจบปกติ (ไม่ break)
Nested For Loops
numbers = [1, 2, 3]
chars = ["a", "b", "c"]
for i in numbers:
for y in chars:
print(i, y)
# Output:
# 1 a
# 1 b
# 1 c
# 2 a
# 2 b
# 2 c
# 3 a
# 3 b
# 3 c
For Loop with enumerate() และ zip()
# enumerate() - ได้ index และ value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# zip() - รวมหลาย iterables
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
2. While Loop (วนจนกว่าเงื่อนไขจะเป็น False)
Basic While Loop
i = 1
while i < 5:
print("Hello world")
i = i + 1 # ⚠️ ต้องเพิ่ม i ไม่งั้น Infinite Loop!
# Output: Hello world x4
While Loop with Else
i = 1
while i < 5:
print("Hello world")
i += 1
else:
print("The execution has ended")
# Hello world x4
# The execution has ended
Break และ Continue
# break - หยุดลูปทันที
my_list = ['a', 'b', 'c', 'd', 'e']
for i in my_list:
if i == 'c':
print("'c' encountered. Breaking.")
break
print(i)
# a b 'c' encountered. Breaking.
# continue - ข้ามรอบนี้ ไปรอบต่อไป
for i in my_list:
if i == 'c':
continue
print(i)
# a b d e (คือ c ถูกข้าม)
For vs When: เลือกใช้อันไหน?
| ลักษณะ | For Loop | While Loop |
|---|---|---|
| รู้จำนวนรอบชัดเจน | ✅ เหมาะสม | ใช้ได้แต่ซับซ้อน |
| ไม่รู้จำนวนรอบ (ขึ้นกับเงื่อนไข) | ใช้ได้ (while True + break) | ✅ เหมาะสม |
| วนผ่าน Collection | ✅ Pythonic | ต้องใช้ index |
| Complex condition | ยาก | ✅ เหมาะสม |
สรุป
- For Loop: ใช้เมื่อรู้จำนวนรอบ หรือ วนผ่าน Collection (List, Tuple, Set, Dict, Range)
- While Loop: ใช้เมื่อไม่รู้จำนวนรอบ ขึ้นกับเงื่อนไขที่เปลี่ยนแปลง
- Else: ทำงานเมื่อลูปจบปกติ (ไม่ได้ Break)
- Break: หยุดลูปทันที
- Continue: ข้ามรอบนี้ ไปรอบถัดไป
- Enumerate/Zip: เครื่องมือช่วย For Loop ให้มีประสิทธิภาพ