Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Assertions ใน Python คืออะไร และทำงานอย่างไร

Assertion: sanity-test หลัง testing เสร็จ

คล้าย raise-if-not ถ้า expression เป็น False → raise AssertionError

ทำงานด้วย assert statement

ใช้ที่ไหน:

  • ต้นฟังก์ชัน: check valid input
  • หลังฟังก์ชัน: check valid output

ตัวอย่าง

x, y = 8, 8
assert x < y, 'x and y are equal'

ผลลัพธ์

AssertionError: x and y are equal

เทียบเท่าโดยไม่ใช้ assert:

if not x < y:
    raise AssertionError('x and y are equal')