Python assert Statement

Python assert function confirms an expression. If the expression fails, the script will exit with an error.

>>> x = 3
>>> assert(x>2)

>>> assert(x<2)
Traceback (most recent call last):
File "", line 1, in 
AssertionError
Using assert for preventive programming:
def cm2inch(h):
assert(h>=0), "height must be positive";
return(h*0.3937);

>>> cm2inch(2)
0.7874
>>> cm2inch(-2)
Traceback (most recent call last):
File "", line 1, in 
File "", line 1, in 
AssertionError: height must be positive












endmemo.com © 2024  | Terms of Use | Privacy | Home