Explain about assert statement?

Assertion :
  • An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.
  • We often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
The assert Statement :
  • When encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
  • Syntax :
    • assert Expression[, Arguments]
  • If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
  • AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
  • Ex :
>>> def addOne(n):
...     assert (n >= 0),"n should be greator than or equal to 0."
...     return n + 1
... 
>>> addOne(1)
2
>>> addOne(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in addOne
AssertionError: n should be greator than or equal to 0.

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?