Nearby lessons
75 of 108Python - Assertions
Detailed Tutorial Notes
PYTHON DEBUGGING BY USING ASSERTIONS
Debugging Python Program by using assert keyword:
The process of identifying and fixing the bug is called debugging.
main.py
assert statement over print() statement is after fixing bug we are not required to delete
problems and disturbs console output.
To overcome this problem we should go for assert statement. The main advantage of
assert statements. Based on our requirement we can enable or disable assert statements.
Hence the main purpose of assertions is to perform debugging. Usully we can perform
debugging either in development or in test environments but not in production
environment. Hence assertions concept is applicable only for dev and test environments
but not for production environment.
Types of assert statements:
There are 2 types of assert statements
- Simple Version
- Augmented Version
- Simple Version: assert conditional_expression
- 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 AssertionError, programmer can analyze the code and can fix the problem. Eg:
1) def squareIt(x):
2) return x**x
3) assert squareIt(2)==4,"The square of 2 should be 4"
4) assert squareIt(3)==9,"The square of 3 should be 9"
5) assert squareIt(4)==16,"The square of 4 should be 16"
6) print(squareIt(2))
7) print(squareIt(3))
8) print(squareIt(4))9)
10) D:\Python_classes>py test.py
11) Traceback (most recent call last):
12) File "test.py", line 4, in <module>
13) assert squareIt(3)==9,"The square of 3 should be 9"
14) AssertionError: The square of 3 should be 915)
main.py
4 9 16
Exception Handling vs Assertions:
Assertions concept can be used to alert programmer to resolve development time errors.
Exception Handling can be used to handle runtime errors.