Understanding Python in one article (7) ----- Assertions

When I was looking at the PyTorch implementation version of U-net today, I found that the relevant grammar of assertion was used in it. Record it here!

1. The grammatical format of assertion

assert <断言判断条件> [,"错误提示消息"]

当表达式为真时,程序继续往下执行;

当表达式为假时,抛出AssertionError错误,并将‘参数’输出。

Two, usage scenarios

Assertions are used to tell developers that an unrecoverable error has occurred in the program. Users can correct or retry predictable errors (such as not finding related files). Assertions are not for this reason.
If the program has no bugs, these assertion conditions will never be triggered, but if the assertion conditions are violated, the program will crash and report an assertion error, telling the developer which "impossible" situation was violated, which can make it easier Track and fix bugs in the program. Assertion statements in python are a debugging aid, not a mechanism for handling runtime errors. The purpose of using assertions is to allow developers to find the root cause of possible bugs more quickly. Unless there are bugs in the program, they will never An assertion error will be thrown.

Three, case

  • Code
def fun1(s):
    n = int(s)
    assert n!= 0, 'n is zero'
    return 10 / n
fun1('0')
  • operation result
AssertionError                            Traceback (most recent call last)
<ipython-input-6-c41609152707> in <module>
      3     assert n!= 0, 'n is zero'
      4     return 10 / n
----> 5 fun1('0')

<ipython-input-6-c41609152707> in fun1(s)
      1 def fun1(s):
      2     n = int(s)
----> 3     assert n!= 0, 'n is zero'
      4     return 10 / n
      5 fun1('0')

AssertionError: n is zero

references

https://zhuanlan.zhihu.com/p/187589076

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/114006994