Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

assert statement trong Python dùng làm gì?

Câu lệnh assert có syntax sau:

assert <some_test>, <message>

Dòng trên đọc như: Nếu <some_test> evaluates to False, exception được raise và <message> sẽ được output.

Nếu chúng ta muốn test code block hoặc expression, chúng ta đặt nó sau từ khóa assert. Nếu test pass hoặc expression evaluates to true, nothing happens. Nhưng nếu test fail hoặc expression evaluates to false, AssertionError được raise và message được print out hoặc evaluated.

Assert statement dùng để catch/test user-defined constraints. Nó dùng để debug code và được insert ở đầu script.

Nó không dùng để catch code errors như x / 0, vì Python tự catch những errors đó.

Code cho trước có thể test dùng assert statement như sau:

x, y = 4, 7
assert x > y, "x has to be smaller than y"

OUTPUT

Traceback (most recent call last):
  File "C:/Users/TutorialsPoint1/~assert2.py", line 2, in 
    assert x > y, "x has to be smaller than y"
AssertionError: x has to be smaller than y