ข้ามไปยังเนื้อหา

Whitespace ที่มีความหมาย

ใน TypeScript การย่อหน้าเป็นแค่เรื่องหน้าตา linter บังคับไว้เพื่อให้อ่านง่าย แต่ compiler ไม่สนใจเลย ต่อให้ไม่ย่อหน้าหรือย่อมั่ว โค้ดก็ยังทำงานเหมือนเดิม

ส่วนใน Python การย่อหน้าเป็นส่วนหนึ่งของ grammar เพราะ interpreter ใช้ตัดสินว่า block เริ่มตรงไหนและจบตรงไหน ไม่มี curly brace และไม่มีคำสั่ง end ให้ยึด

นี่ไม่ใช่ความแปลกประหลาด แต่เป็นการตัดสินใจออกแบบโดยเจตนา เพื่อบังคับให้ code อ่านง่ายโดยอัตโนมัติ

TypeScript
// TypeScript: braces delimit every block
function classify(n: number): string {
if (n > 0) {
return "positive";
} else if (n < 0) {
return "negative";
} else {
return "zero";
}
}
for (let i = 0; i < 3; i++) {
if (i % 2 === 0) {
console.log(`${i} is even`);
}
}
Python
# Python: indentation delimits every block
def classify(n: int) -> str:
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
for i in range(3):
if i % 2 == 0:
print(f"${i} is even")

ข้อแตกต่างด้าน syntax ที่ควรสังเกต:

  • คำว่า function กลายเป็น def ตามด้วยชื่อฟังก์ชันและเครื่องหมายโคลอน
  • else if ใน TypeScript กลายเป็น elif ใน Python (ไม่มี else if แยกต่างหาก)
  • ทุกบรรทัดที่เปิด block ต้องลงท้ายด้วยเครื่องหมายโคลอน (:)
  • มาตรฐานการย่อหน้าคือ 4 ช่องว่าง การใช้ tab ได้แต่การผสม tab กับ space จะทำให้เกิด TabError

ถ้าย่อหน้าผิด Python จะ raise IndentationError ก่อนที่ code จะรันด้วยซ้ำ นี่คือเทียบเท่ากับ error “unexpected token” ของ TypeScript ตอน compile

TypeScript
// TypeScript: this still runs (just ugly style)
function add(a: number, b: number) {
return a + b; // no indent — TS doesn't care
}
Python
# Python: this raises IndentationError
def add(a: int, b: int) -> int:
return a + b # missing indent — SyntaxError at parse time
# Correct version:
def add(a: int, b: int) -> int:
return a + b # 4 spaces

การซ้อนบล็อกทำได้โดยเพิ่มระดับการย่อหน้าสำหรับแต่ละบล็อก Python parser ติดตามระดับการย่อหน้า จึงไม่มีขีดจำกัดในการซ้อน แต่ Zen of Python แนะนำให้รักษาระดับความลึกให้น้อยที่สุด

TypeScript
// TypeScript nested blocks
function processMatrix(matrix: number[][]): void {
for (const row of matrix) {
for (const cell of row) {
if (cell > 0) {
console.log(`positive: ${cell}`);
}
}
}
}
Python
# Python nested blocks
def process_matrix(matrix: list[list[int]]) -> None:
for row in matrix:
for cell in row:
if cell > 0:
print(f"positive: ${cell}")
# Python uses indentation — no curly braces needed
def greet(name):
if name:
print(f"Hello, {name}!")
else:
print("Hello, stranger!")
greet("Alice")
greet("")
for i in range(3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
Python ใช้อะไรแทน curly braces เพื่อกำหนดขอบเขตของ code block?
Python จะ raise error อะไรเมื่อการย่อหน้าผิด?
ใน Python คำสั่งที่เทียบเท่า `else if` ของ TypeScript คืออะไร?
ทุกบรรทัดที่เปิด block ใน Python ต้องลงท้ายด้วยอักขระใด?