斷言的最簡單的方法就是把它比作 raise-if 語句 (或者更準確,加 raise-if-not 聲明). 一個表達式進行測試,如果結果出現(xiàn) false,將引發(fā)異常。
當它遇到一個斷言語句,Python評估計算之后的表達式,希望是 true 值。如果表達式為 false,Python 觸發(fā) AssertionError 異常。
assert Expression[, Arguments]
如果斷言失敗,Python使用 ArgumentExpression 作為AssertionError異常的參數(shù)。AssertionError異??梢员徊东@,并用 try-except語句處理類似其他異常,但是,如果沒有處理它們將終止該程序并產生一個回溯。
這里是一個把從開氏度到華氏度的溫度轉換函數(shù)。
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
32.0 451 Traceback (most recent call last): File "test.py", line 9, in print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero!