ใน Python program สามารถ indent code ด้วย spaces หรือ tabs ได้ ถ้าพยายามใช้ทั้งคู่ใน block โค้ดเดียวกัน จะเจอ error TabError: inconsistent use of tabs and spaces in indentation
คู่มือนี้อธิบาย error นี้หมายถึงอะไร ทำไมจึงเกิดขึ้น พร้อมตัวอย่าง ช่วยแก้ในโค้ดของคุณ
TabError: inconsistent use of tabs and spaces in indentation
Python style guide แนะนำ spaces เป็น preferred indentation method แต่สามารถใช้ tabs หรือ spaces ได้
Indentation สำคัญใน Python เพราะภาษาไม่ขึ้นกับ syntax เช่น curly braces บอกว่า block เริ่มจบที่ไหน Indents บอก Python ว่าบรรทัดไหนเป็นส่วนของ block ไหน
โปรแกรมตัวอย่าง:
numbers = [8, 7, 9, 8, 7]
def calculate_average_age():
average = sum(numbers) / len(numbers)
print(average)
ไม่มี indentation ไม่รู้ว่าบรรทัดไหนเป็นส่วนของ calculate_average_age function และบรรทัดไหนเป็นส่วนของ main program
ต้องเลือกใช้ spaces หรือ tabs อย่างใดอย่างหนึ่ง อย่า mix tabs และ spaces การทำจะสับสน Python interpreter และก่อให้เกิด TabError: inconsistent use of tabs and spaces in indentation error
ตัวอย่างสถานการณ์ (An Example Scenario)
สร้างโปรแกรมคำนวณมูลค่ารวม purchases ที่ร้านโดนัท เริ่มกำหนดลิสต์ purchases:
purchases = [2.50, 4.90, 5.60, 2.40]
กำหนดฟังก์ชันคำนวณ total ของ "purchases" list:
def calculate_total_purchases(purchases):
total = sum(purchases)
return total
Function รับ 1 parameter: ลิสต์ purchases ที่ต้องการคำนวณ total คืนค่า total value ของลิสต์ที่ระบุเป็น parameter
ใช้ sum() method คำนวณ total ตัวเลขใน "purchases" list
ถ้า copy code snippet นี้ไป text editor อาจสังเกต "return total" indented ด้วย spaces แต่ "total = sum(purchases)" ใช้ tabs สำหรับ indentation นี่คือ distinction สำคัญ
เรียก function และพิมพ์ค่าที่คืนคอนโซล:
total_purchases = calculate_total_purchases(purchases) print(total_purchases)
โค้ดเรียก calculate_total_purchases() คำนวณ total value purchases ทั้งหมดที่ร้านโดนัท พิมพ์ค่านั้นคอนโซล รันโค้ด:
File "test1.py", line 5 return total ^ TabError: inconsistent use of tabs and spaces in indentation
โค้ด error
วิธีแก้ (The Solution)
เราใช้ spaces และ tabs indent โค้ด ใน Python program ควรติดกับ spaces หรือ tabs อย่างใดอย่างหนึ่ง
แก้โค้ด: เปลี่ยน function ให้ใช้ spaces เพียงอย่างเดียว:
def calculate_total_purchases(purchases):
total = sum(purchases)
return total
โค้ดใช้ 4 spaces indentation รันโปรแกรมด้วย indentation ใหม่:
15.4
โปรแกรมคำนวณ total value donut purchases สำเร็จ
ใน IDLE editor สามารถลบ indentation ของ block code ได้โดย:
- Select code ที่ต้องการลบ indentation
- Click "Menu" → "Format" → "Untabify region"
- Insert indentation type ที่ต้องการ
วิธีนี้สะดวกสำหรับ fix formatting ใน document สมมติใช้ IDLE editor editors อื่นๆ เช่น Sublime Text มีวิธีของตัวเองเปลี่ยน indentation ในไฟล์
สรุป
Python TabError: inconsistent use of tabs and spaces in indentation error เกิดเมื่อพยายาม indent code ด้วยทั้ง spaces และ tabs
แก้ error: ติดกับ spaces หรือ tabs ในโปรแกรม แล้วแทนที่ tabs หรือ spaces ที่ไม่ใช้ preferred indentation method ตอนนี้คุณมีความรู้แก้ error นี้อย่าง professional programmer แล้ว!