Python ใช้ Indentation (Whitespace) กำหนด Block ของโค้ด แทน Curly Braces {} ใน C/Java
กฎหลัก
- ก่อน Block ใช้
:(Colon) - Statement ใน Block ต้อง Indent เท่ากัน (ปกติ 4 Spaces)
- Dedent (ลด Indent) = จบ Block
ตัวอย่าง
num = int(input("enter number: "))
if num % 2 == 0:
if num % 3 == 0:
print("Divisible by 3 and 2")
else:
print("Divisible by 2 not by 3")
else:
if num % 3 == 0:
print("Divisible by 3 not by 2")
else:
print("Not divisible by 2 or 3")
ข้อดี
- บังคับ Code Style ให้สม่ำเสมอ (Readable)
- ลด Syntax Noise (ไม่ต้อง
{},begin/end) - Structure ชัดเจน ตาม Visual Hierarchy
ข้อควรระวัง
- Mix Tab/Space →
IndentationError(Python 3 ห้ามผสม) - Copy-Paste ต้องระวัง Indentation Level
- ใช้ Editor ที่รองรับ Python (Auto-indent, Show Whitespace)