IKH

Assert Types

There are 2 types of assert statements

1.Simple Version

2.Augmented Version

1.Simple Version:

assert conditional_expression

2.Augmented Version:

assert conditional_expression,message

conditional_expression will be evaluated and if it is true then the program will be continued.

if it is false then the program will be terminated by raising assertionerror.

By seeing assertioneror, programmer can analyze the code and can fix the problem.

Example

Python
 def squareIt(x): 
 return x**x
 assert squareIt(2)==4,"The square of 2 should be 4" 
 assert squareIt(3)==9,"The square of 3 should be 9" 
 assert squareIt(4)==16,"The square of 4 should be 16" 
 print(squareIt(2)) 
 print(squareIt(3)) 
 print(squareIt(4))  

 D:\Python_classes>py test.py 
 Traceback (most recent call last): 
 File "test.py", line 4, in <module> 
 assert squareIt(3)==9,"The square of 3 should be 9" 
 AssertionError: The square of 3 should be 9 
 
 def squareIt(x): 
 return x*x 
 assert squareIt(2)==4,"The square of 2 should be 4" 
 assert squareIt(3)==9,"The square of 3 should be 9" 
 assert squareIt(4)==16,"The square of 4 should be 16" 
 print(squareIt(2)) 
 print(squareIt(3)) 
 print(squareIt(4))
 

output

PowerShell
4 
9 
16

Name
Email
Phone

Report an error