>>> number = input('Enter a positive number:')Enter a positive number:-1>>> assert (number > 0), 'Only positive numbers are allowed!'Traceback (most recent call last):File "<stdin>", line 1, in <module>AssertionError: Only positive numbers are allowed!>>>
32.0451Traceback (most recent call last):File "test.py", line 9, in <module>print KelvinToFahrenheit(-5)File "test.py", line 4, in KelvinToFahrenheitassert (Temperature >= 0),"Colder than absolute zero!"AssertionError: Colder than absolute zero!
>>>this_is_very_complex_function_result = 9>>>c = this_is_very_complex_function_result>>>test_us = (c < 4)
>>> #first we try without assert>>>if test_us == True:print("YES! I am right!")else:print("I am Wrong, but the program still RUNS!")
I am Wrong, but the program still RUNS!
>>> #now we try with assert>>> assert test_usTraceback (most recent call last):File "<pyshell#52>", line 1, in <module>assert test_usAssertionError>>>
if __debug__:if not <expression>: raise AssertionError
您可以使用扩展表达式传递可选消息:
if __debug__:if not (expression_1): raise AssertionError(expression_2)
在Python解释器中尝试:
>>> assert True # Nothing happens because the condition returns a True value.>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.Traceback (most recent call last):File "<stdin>", line 1, in <module>AssertionError
>>> assert (1==2), ("This condition returns a %s value.") % "False"Traceback (most recent call last):File "<stdin>", line 1, in <module>AssertionError: This condition returns a False value.
调试目的
如果你想知道什么时候使用assert语句。举一个现实生活中使用的例子:
*当您的程序倾向于控制用户输入的每个参数或其他任何参数时:
def loremipsum(**kwargs):kwargs.pop('bar') # return 0 if "bar" isn't in parameterkwargs.setdefault('foo', type(self)) # returns `type(self)` value by defaultassert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())
*另一种情况是在数学上,当0或非正作为某个方程的系数或常数时:
def discount(item, percent):price = int(item['price'] * (1.0 - percent))print(price)assert (0 <= price <= item['price']),\"Discounted prices cannot be lower than 0 "\"and they cannot be higher than the original price."
return price
*甚至是布尔实现的简单示例:
def true(a, b):assert (a == b), "False"return 1
def false(a, b):assert (a != b), "True"return 0
import MyClasss
def code_it(self):testObject = self.object1.object2 # at this point, program doesn't know that testObject is a MyClass object yetassert isinstance(testObject , MyClasss) # now the program knows testObject is a MyClass objecttestObject.do_it() # from this point on, PyCharm will be able to auto-complete when you are working on testObject
class PositiveInt(int):# int is immutable, so we have to override new and not initdef __new__(cls, value):if value <= 0:raise ValueError(f"{value} is not positive")assert value > 0, "value must be positive"return super(PositiveInt, cls).__new__(cls, value)