Python 断言
时间:2020-02-23 14:42:26 来源:igfitidea点击:
在本教程中,我们将学习python assert关键字。
Python assert可以帮助我们调试代码。
如果要模拟代码在哪个阶段发生的情况,则可以在代码中使用python assert语句。
使用Python中的assert关键字可以检测到对任何变量赋值的期望是什么?
Python断言
以下是python assert语句的基本结构:
assert condition
您也可以使用assert语句发送信息,以更好地理解代码错误。
以下是使用assert语句给出消息的方式:
assert condition, your message
Python断言语句
Python断言语句带有一个条件,该条件必须为true。
如果条件为真,则表示变量值的确定是正确的,则程序将平稳运行,并执行下一条语句。
但是,如果条件为假(这意味着我们的代码中存在一些错误),则会引发异常。
Python断言示例
我们要编写一个函数,该函数将返回两个数字的商。
以下是代码:
# defining the function definition def divide(num1, num2): assert num2 > 0 , "Divisor cannot be zero" return num1/num2 # calling the divide function a1 = divide(12,3) # print the quotient print(a1) # this will give the assertion error a2 = divide(12,0) print(a2)
如果我们运行上面的代码,则输出将是:
4.0 Traceback (most recent call last): File "D:/T_Code/PythonPackage3/Assert.py", line 10, in a2 = divide(12,0) File "D:/T_Code/PythonPackage3/Assert.py", line 3, in divide assert num2>0 , "Divisor cannot be zero" AssertionError: Divisor cannot be zero
在以上代码的第三行中,您可以看到assert语句。
在这一行中,检查变量num2的值是否大于0。
如果大于零,即条件为true,则不会发生任何问题,并相应地获得输出。
但是,当我们使用第二个参数0调用函数divide()时,则断言条件为false。
这就是为什么我们在python assert语句的消息部分中写到" AssertionError"并给出消息"除数不能为零"的原因。
阅读有关python异常处理的更多信息。
带有变量替换的Python断言示例
考虑下面的代码,我们试图找到方程式(b2-4ac)的平方根。
import math def sqrt(a,b,c): assert b*b >= 4*a*c, "Cannot find square root of negative number, found %s < %s" % (b*b, 4*a*c) return math.sqrt(b*b - 4*a*c) print(sqrt(10, 12, 3)) # this will cause assertion error print(sqrt(-4, 5, -3))