Syntax: assert
ถ้า condition เป็น False → raise AssertionError พร้อม message
ใช้สำหรับ:
- Debugging code
- ตรวจสอบ user-defined constraints (preconditions, postconditions)
- ไมใช้สำหรับ catch code errors (เช่น x/0) เพราะ Python จัดการเอง
ตัวอย่าง
x, y = 4, 7 assert x > y, "x has to be smaller than y"
ผลลัพธ์
AssertionError: x has to be smaller than y
เทียบเท่ากับ:
if not x < y:
raise AssertionError('x and y are equal')