Assert Statement in Python for Error Detection

We all are familiar with the word “debugging”. This term includes a variety of steps to debug a given code. One such part is the “assert statement”. In this tutorial, we will learn about the application and implementation of the assert statement in Python to calculate percentage error.

This statement is widely used when we want to imply constraints to the working of the program.

Syntax:  assert <Condition>

Error Detection in Python – Assert Statement

Let us suppose that we want to compute the percentage of marks obtained in a subject. It may happen that the values of variables maxmarks and marks entered by the user may not be in proper range. It may be negative or greater than the maximum marks.

Here the assert statement comes handy which checks the fulfilment of input with the set constraints.

Error Detection in Python using assert statement

Here is the source code in Python to detect error in calculation ( Percentage error ) using assert statement

def percent(marks, maxmarks):
    return percentv

#first constraint application using assert statement
assert maxmarks>=0 and maxmarks<=500 # here assertion error is raised if the input is not satisfying contraints

#second contraint application
assert marks>=0 and marks<=maxmarks # here assertion error is raised if the input is not satisfying the constraints

percentage=percent(marks, maxmarks)
print "percentage : ",percentage
Testcase 1: 150
Assertion error ; line 13
Testcase 2: 150
percentage :  33.3333333333

If both the assertion hold Boolean value True, the function displays percentage as the output as seen in Testcase 2 and in case any of then retains a Boolean value False, then assertion error is raised as seen in Testcase 1.

Also, learn,

Leave a Reply

Your email address will not be published. Required fields are marked *