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 a proper range. It may be negative or greater than the maximum marks.

Here the assert statement comes in 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):
    percentv = (marks / maxmarks) * 100
    return percentv

# Main
maxmarks = float(input("Enter the maximum marks: "))  # Added a prompt for user input
# First constraint application using assert statement
assert 0 <= maxmarks <= 500  # Here assertion error is raised if the input is not satisfying constraints

marks = float(input("Enter the marks obtained: "))  # Added a prompt for user input
# Second constraint application
assert 0 <= 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
            155
Output:   
Assertion error ; line 13
Testcase 2: 150
            50
Output:
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 *