用Python声明语句

In programming assertions are used to verify whether a specified condition is true or not. For example if we have a function to add two numbers, before using the + operator to add the two numbers provided by user, we can use an assertion to check if the values input are numbers only and not alphabets or special characters.

在编程中,断言用于验证指定条件是否为真。 例如,如果我们有一个将两个数字相加的函数,则在使用+运算符将用户提供的两个数字相加之前,可以使用一个断言来检查输入的值是否仅是数字,而不是字母或特殊字符。

Assert statement contains a Boolean expression that checks for trueness of a condition and returns true if found valid else returns false.

声明语句包含一个布尔表达式,该布尔表达式检查条件的正确性,如果发现有效,则返回true,否则返回false。

When an Assertion is used in a program, then in case of positive assertion the program will continue its execution normally whereas in case of negative assertion the program will stop its execution and throw an error.

当在程序中使用断言时,则在肯定断言的情况下,程序将继续正常执行,而在否定断言的情况下,程序将停止执行并抛出错误。

Python assert语句 (Python assert statement)

In python there is a built-in assert statement which can be used to implement assertions in your program. The assert statement in python takes a condition or an expression as an argument and expects it to be true for the program to continue its execution. If the condition/expression is false, the assert statement will throw an AssertionError, which as a result interrupts the normal execution of the program.

在python中,有一个内置的assert语句,可用于在程序中实现断言。 python中的assert语句采用条件或表达式作为参数,并希望它为true才能使程序继续执行。 如果条件/表达式为false,则assert语句将引发AssertionError ,从而中断程序的正常执行。

Assertion in python is the pythonic way of applying conditions for validations where usually if...else conditions are used.

python中的断言是将条件应用于验证的pythonic方式,通常if...else条件的情况下。

Let's take a simple example to understand when and where to use assert statement. If you have a program to take Password as input from a user where the input should be checked whether it's a strong password and if found strong it should be stored, else the user should be asked to re-enter the password. In this case we can use an assert statement to apply various conditions to the input password value to check if it's a strong password. If the conditions return true then the program will continue to store the password else the assert statement will throw an AssertionError. Makes sense!

让我们举一个简单的例子来了解何时以及在何处使用assert语句。 如果您有一个程序可以从用户那里获取密码作为输入,应检查该输入是否为强密码,如果存储的是强密码,则应将其存储,否则应要求用户重新输入密码。 在这种情况下,我们可以使用assert语句将各种条件应用于输入的密码值,以检查其是否为强密码。 如果条件返回true,则程序将继续存储密码,否则assert语句将引发AssertionError 。 说得通!

assert语句的语法: (Syntax of the assert statement:)

Assert statement can be declared in two ways:

可以通过两种方式声明断言:

assert <condition>
# with condition and error message
assert <condition>, <error message>

In the first type of syntax, the assert statement will only check the condition and when the condition will be false it will raise an assertion error. But in the second case, assert statement will also print a message along with assertion error when the condition is false.

在第一种语法中,assert语句将仅检查条件,当条件为false时,将引发断言错误。 但是在第二种情况下,当条件为false时,assert语句还将打印一条消息以及断言错误。

时间为例! (Time for an example!)

Let's take a simple example where we will be defining a function to find percentage of marks scored where a list of marks scored out of 100 will be provided. We will be using assert statement to make sure no marks entry in the list contains negative marks.

让我们举一个简单的示例,在该示例中,我们将定义一个函数以找到得分的百分比,并提供得分超过100的得分列表。 我们将使用assert语句来确保列表中没有标记条目包含负号。

演示地址

As you can see in the program above, when we provide 1 negative value the program fails with an AssertionError, else it executed successfully and returns the result.

正如您在上面的程序中看到的那样,当我们提供1个负值时,程序将失败并显示AssertionError ,否则它将成功执行并返回结果。

Now lets update the above program to include a message in the assert statement to be shown along with the assertion error.

现在让我们更新上面的程序,以便在assert语句中包含一条消息,以与断言错误一起显示。

# function to calculate percentage, given a list of marks out of 100
def percentage(marks):
  for m in marks:
    # marks should always be a positive value
    assert m > 0, "Only positive values allowed"
  return (sum(marks)/len(marks))
  
print(percentage([90,93,99,95,-94]))

Traceback (most recent call last): File "/tmp/sessions/2ce06e6f313b60f6/main.py", line 8, in print(percentage([90,93,99,95,-94])) File "/tmp/sessions/2ce06e6f313b60f6/main.py", line 5, in percentage assert m > 0, "Only positive values allowed" AssertionError: Only positive values allowed

追溯(最近一次通话最近):文件“ /tmp/sessions/2ce06e6f313b60f6/main.py”,第8行,在 print(percentage([90,93,99,95,-94]))文件“ /tmp/sessions/2ce06e6f313b60f6/main.py”,第5行,以百分比断言m> 0,“仅允许正值” AssertionError:只允许正值

要记住的一些重要点! (Some important points to remember!)

Assert is not same as try...except. try...except is used for dealing with a recoverable error which can be followed by a corrective measure while assert statement is used for the errors which either can't be recovered or any corrective measure is not required for them.

断言与try ... except不同 。 try ... except用于处理可恢复的错误,之后可以采取纠正措施,而assert语句用于无法恢复的错误或不需要采取任何纠正措施的错误。

Assert is a statement not a function, hence never use it with parentheses. If you try to execute the following assert(condition, message), assert will execute with a tuple as the first argument. It will take (condition, message) as a tuple input.

断言不是函数 ,因此不要在括号中使用它。 如果您尝试执行以下assert(condition, message) ,则assert将以元组作为第一个参数执行。 它将(condition, message)作为元组输入。

The behaviour of an assert statement is like the following code:

assert语句的行为类似于以下代码:

if not condition:
    raise AssertionError()

Although it is not entirely this but more or else behaves like this.

尽管这不完全是这样,但更多的还是这样。

If you have a program with many assert statements and you want to disable all the assert statements, run the python script in optimized mode which can be done using the -o flag.

如果您的程序包含许多assert语句,并且想要禁用所有assert语句 ,请以优化模式运行python脚本,可以使用-o标志来完成此操作。

python -o yourscript.py

Because in optimized mode __debug__ is false and as per the official documentation of python, assert statement is equivalent to:

因为在优化模式下__debug__false,并且根据python的官方文档,所以assert语句等效于:

if __debug__:
   if not expression: raise AssertionError

Hence if __debug__ is false, assert statements are disabled.

因此,如果__debug__为false,则断言语句将被禁用。

翻译自: https://www.studytonight.com/python/python-assert

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值