Skip to content

บทที่ 2.1: การควบคุมทิศทางและการเลือกทำ (Conditions & Match)

เอกสารนี้อธิบายถึงการควบคุมโครงสร้างการทำงานด้วยคำสั่งเงื่อนไข if, elif, else รวมถึงการใช้งาน Structural Pattern Matching (match-case) ซึ่งเป็นฟีเจอร์การตรวจจับรูปแบบข้อมูลขั้นสูง


1. คำสั่งเงื่อนไขพื้นฐาน (if, elif, else)

คำสั่งเงื่อนไขใช้สำหรับกำหนดเงื่อนไขให้โปรแกรมเลือกประมวลผลคำสั่งตามผลลัพธ์ของตรรกศาสตร์ (True หรือ False)

1.1 โครงสร้างคำสั่ง

score = 75

if score >= 80:
    print("เกรด A")
elif score >= 70:
    print("เกรด B")
elif score >= 60:
    print("เกรด C")
else:
    print("เกรด F")
# Output: เกรด B

1.2 เงื่อนไขซ้อนเงื่อนไข (Nested Conditions)

age = 20
has_license = True

if age >= 18:
    if has_license:
        print("อนุญาตให้ขับขี่ได้")
    else:
        print("อายุถึงเกณฑ์ แต่ไม่มีใบขับขี่")
else:
    print("ไม่อนุญาตให้ขับขี่ (อายุไม่ถึง)")

2. นิพจน์เงื่อนไขแบบสั้น (Ternary Operator)

Ternary Operator ช่วยให้สามารถเขียนเงื่อนไข if-else แบบสั้นภายในบรรทัดเดียว เหมาะสำหรับการกำหนดค่าให้ตัวแปร

2.1 ไวยากรณ์

value_if_true if condition else value_if_false

age = 20

# เขียนแบบสั้น
status = "Adult" if age >= 18 else "Minor"
print(status)  # Output: Adult

3. Structural Pattern Matching (match-case)

ฟีเจอร์ที่เพิ่มเข้ามาใน Python 3.10+ ช่วยให้สามารถเปรียบเทียบค่าและตรวจสอบรูปแบบโครงสร้างข้อมูล (Pattern Matching) ได้อย่างมีประสิทธิภาพ ทำงานคล้าย switch-case ในภาษาอื่นแต่มีความสามารถสูงกว่า

3.1 การเปรียบเทียบค่าทั่วไป (Basic Matching)

status_code = 404

match status_code:
    case 200:
        print("Success")
    case 400:
        print("Bad Request")
    case 404:
        print("Not Found")
    case 500:
        print("Internal Server Error")
    case _:  # Wildcard (_) ทำหน้าที่เหมือน else
        print("Unknown Status")

3.2 การรวมเงื่อนไขและการใช้ Guard (if)

command = "start"

match command:
    case "start" | "go" | "run":  # ใช้ | เชื่อมหลายเงื่อนไข
        print("กำลังเริ่มทำงาน...")
    case "stop" | "end":
        print("หยุดการทำงาน")
    case _:
        print("ไม่รู้จักคำสั่ง")

3.3 การจับรูปแบบโครงสร้างข้อมูล (Pattern Matching Sequence & Dict)

สามารถแกะค่า (Unpack) ข้อมูลจาก Tuple, List หรือ Dict พร้อมใช้ Guard (if) เพิ่มเติมได้:

point = (0, 5)

match point:
    case (0, 0):
        print("จุดศูนย์กลาง (Origin)")
    case (0, y):
        print(f"อยู่บนแกน Y ที่ตำแหน่ง {y}")
    case (x, 0):
        print(f"อยู่บนแกน X ที่ตำแหน่ง {x}")
    case (x, y) if x == y:
        print(f"อยู่บนเส้นทะแยงมุม X = Y ({x}, {y})")
    case (x, y):
        print(f"พิกัดทั่วไป ({x}, {y})")