🐍 บทที่ 6: คำสั่งควบคุมและการวนซ้ำใน Python

📌 คำสั่งควบคุมคืออะไร?

คำสั่งควบคุม (Control Flow) ใน Python ใช้สำหรับควบคุมการทำงานของโปรแกรม โดยมีคำสั่งเงื่อนไข (`if`, `elif`, `else`) และคำสั่งวนซ้ำ (`for`, `while`)

🛠️ คำสั่งเงื่อนไข (`if`, `elif`, `else`)

ใช้เพื่อตรวจสอบเงื่อนไขและเลือกทางเดินของโปรแกรม

# ตัวอย่างการใช้ if-else
score = int(input("ป้อนคะแนนของคุณ: "))

if score >= 80:
    print("คุณได้เกรด A")
elif score >= 70:
    print("คุณได้เกรด B")
elif score >= 60:
    print("คุณได้เกรด C")
elif score >= 50:
    print("คุณได้เกรด D")
else:
    print("คุณได้เกรด F")
        

✅ เมื่อป้อน `85` จะได้ผลลัพธ์:

คุณได้เกรด A
        

🔄 คำสั่งวนซ้ำ (`for` และ `while`)

ใช้สำหรับทำซ้ำชุดคำสั่ง

📌 `for` loop

# วนลูป 5 ครั้ง
for i in range(5):
    print("รอบที่:", i)
        

✅ ผลลัพธ์:

รอบที่: 0
รอบที่: 1
รอบที่: 2
รอบที่: 3
รอบที่: 4
        

📌 `while` loop

# ใช้ while loop
count = 0
while count < 3:
    print("Hello, Python!")
    count += 1
        

✅ ผลลัพธ์:

Hello, Python!
Hello, Python!
Hello, Python!
        

🛑 การใช้ `break` และ `continue`

`break` ใช้เพื่อออกจากลูปก่อนเวลาที่กำหนด ส่วน `continue` ใช้เพื่อข้ามรอบนั้น ๆ

📌 ใช้ `break`

for i in range(5):
    if i == 3:
        break
    print(i)
        

✅ ผลลัพธ์:

0
1
2
        

📌 ใช้ `continue`

for i in range(5):
    if i == 2:
        continue
    print(i)
        

✅ ผลลัพธ์:

0
1
3
4
        

🧮 การใช้ `for` ร่วมกับ `list` และ `dict`

📌 วนลูปใน `list`

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
        

✅ ผลลัพธ์:

apple
banana
cherry
        

📌 วนลูปใน `dictionary`

person = {"name": "Jhon", "age": 21}

for key, value in person.items():
    print(key, ":", value)
        

✅ ผลลัพธ์:

name : Jhon
age : 21
        

📌 สรุป

  • ✅ ใช้ `if`, `elif`, `else` เพื่อกำหนดเงื่อนไข
  • ✅ ใช้ `for` และ `while` loop เพื่อทำซ้ำ
  • ✅ ใช้ `break` เพื่อหยุดลูป และ `continue` เพื่อข้ามรอบปัจจุบัน
  • ✅ ใช้ `for` loop กับ `list` และ `dictionary`
🔙 ย้อนกลับ 📖 ไปยังบทถัดไป