Control Flow
Control flow: แนวคิดเดียวกัน แต่ syntax สะอาดกว่า
หัวข้อที่มีชื่อว่า “Control flow: แนวคิดเดียวกัน แต่ syntax สะอาดกว่า”Control flow ของ TypeScript ย้ายมา Python ได้แทบจะคำต่อคำ จุดต่างที่ใหญ่ที่สุดล้วนเป็นเรื่องผิวเผิน คือไม่มีปีกกา (การย่อหน้าคือโครงสร้าง) ใช้ elif แทน else if และใช้ match/case แทน switch
อีกจุดที่ต้องปรับคือ ลูป for ของ Python เป็น for ... in เสมอ ไม่มีลูปสไตล์ C แบบ for (let i = 0; ...) ให้เขียน
if / elif / else
หัวข้อที่มีชื่อว่า “if / elif / else”// TypeScriptconst score: number = 85;let grade: string;
if (score >= 90) { grade = "A";} else if (score >= 80) { grade = "B";} else if (score >= 70) { grade = "C";} else { grade = "F";}
console.log(`Grade: ${grade}`); // Grade: B# Pythonscore: int = 85
if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"
print(f"Grade: {grade}") # Grade: Bfor … in และ range()
หัวข้อที่มีชื่อว่า “for … in และ range()”for ของ Python วนบน iterable เสมอ จะเป็น list, string, dict หรือ range ก็ได้ ไม่มีลูปแบบไล่ index สไตล์ C ให้ใช้ ถ้าต้องการ index ด้วยให้เรียก enumerate()
// TypeScript// Indexed loopfor (let i = 0; i < 5; i++) { console.log(i);}
// for...of over arrayconst fruits = ["apple", "banana", "cherry"];for (const fruit of fruits) { console.log(fruit);}
// Index + valuefruits.forEach((fruit, i) => console.log(i, fruit));# Python# range() replaces the C-style for loopfor i in range(5): # 0, 1, 2, 3, 4 print(i)
# Iterate over any iterable directlyfruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit)
# Index + value with enumerate()for i, fruit in enumerate(fruits): print(i, fruit)range(start, stop, step) เทียบกับรูปแบบฝั่ง TypeScript ได้ตรง ๆ:
| TypeScript | Python |
|---|---|
for (let i = 0; i < 10; i++) | for i in range(10) |
for (let i = 1; i <= 10; i++) | for i in range(1, 11) |
for (let i = 0; i < 10; i += 2) | for i in range(0, 10, 2) |
for (let i = 10; i > 0; i--) | for i in range(10, 0, -1) |
while ทำงานเหมือนกันทุกอย่าง คือวนไปจนกว่าเงื่อนไขจะเป็น false
// TypeScriptlet n: number = 1;while (n <= 5) { console.log(n); n++;}# Pythonn: int = 1while n <= 5: print(n) n += 1 # no ++ operator in Pythonสังเกตว่า Python ไม่มี operator ++ หรือ -- ต้องใช้ += 1 และ -= 1 แทน
match / case — switch ของ Python
หัวข้อที่มีชื่อว่า “match / case — switch ของ Python”Python 3.10 เพิ่ม match/case เข้ามา ซึ่งทำได้มากกว่า switch ของ TypeScript เพราะรองรับทั้ง OR pattern ด้วย |, wildcard _ และ structural pattern matching คือ match ตามรูปร่างของ object ได้เลย
// TypeScript switchconst command: string = "quit";
switch (command) { case "start": console.log("Starting..."); break; case "stop": case "quit": console.log("Stopping"); break; default: console.log(`Unknown: ${command}`);}# Python match/case (Python 3.10+)command: str = "quit"
match command: case "start": print("Starting...") case "stop" | "quit": # OR pattern — no fallthrough needed print("Stopping") case _: # wildcard — like default print(f"Unknown: {command}")ต่างจาก switch ตรงที่ match ไม่ fall through จึงไม่ต้องเขียน break เลยสักที่ ถ้าอยากรวมหลาย case เข้าด้วยกันก็ใช้ | คั่นใน case เดียว
ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”score = 85if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"print(f"Grade: {grade}")
# for + rangeprint("Counting:")for i in range(1, 6): print(f" {i}")
# for + enumeratefruits = ["apple", "banana", "cherry"]print("Fruits:")for i, fruit in enumerate(fruits): print(f" {i}: {fruit}")
# match/casefor cmd in ["start", "quit", "help"]: match cmd: case "start": result = "Starting..." case "stop" | "quit": result = "Stopping" case _: result = f"Unknown: {cmd}" print(result)Loading Python runtime (first run only)…