Methods and Functions

Python Assert Statement

To facilitate the use of the assertion condition in its programs, python provides programmers with its built-in assert statement called as assert python. Upon encountering the assert statement, python evaluates the truth value of the accompanying and supposes it to be true. Should the value get returned as false, python halts the execution of the program in question and raises an AssertionError exception.

Assert Python

Assertions are defined as statements that serve the purpose of specifying an indisputable fact within your program. In other words, assertions can also be visualized as sanity checks that the programmer can invoke at their will once they are done with the testing of their program. For instance, while defining a division function, one can use the python assert statement to state that the value of the divisor can not be equal to zero as that is a universally established truth. 

assert python

In python, assertions are regarded as boolean expressions that are primarily employed to check whether the conditions specified in the program return true or not. If the value returned is true, then the program concerns itself with executing the subsequent lines of code. However, if the value returned is false, then the program halts, raises an exception, and throws an error. In that sense, the assert statement can be considered as a debugging tool for it halts the execution of the program as soon as it encounters an error.
The following flowchart is an accurate representation of the working of the assert statement within python.

Python Assert

The syntax for assert in python is stated as follows:

                    

assert <condition>
assert <condition>, <error message>

In the event that the assertion provided by the programmer fails to hold true, python makes use of ArgumentExpression as the argument for the exception (AssertionError) that it raises. Like other exceptions, AssertionError can also be handled with the help of the try-except statement. However, if these exceptions are not handled, they will cause the program to terminate and generate a traceback in their wake. 

From the syntax stated above, it is clear that there are broadly two kinds of way to make use of the assert statement:

  1. The programmer provides the assert statement with a condition and the condition is not met then the execution of the program comes to a halt. An AssertionError exception is raised in this situation.
  2. One has the liberty of providing both a condition as well as an optional error message to the assert statement. In the event that the condition specified is not met, assert not only halts the program to raise the AssertionError exception, but also displays the error message that was passed on to it as an argument.

Assert in python Examples

  1.  In this example, we will take into account a function that will compute the average of all those values that are provided to it by the user. Care should be taken to ensure that the value is not an empty list. This parameter will be evaluated with the help of the assert statement, and should the length of the passed list turn out to be zero, the program will come to a halt.
                        
    
    def avg(marks):
        assert len(marks) != 0
        return sum(marks)/len(marks)
    
    mark1 = []
    print("Average of mark1:",avg(mark1))

    Upon running this code snippet, we will obtain the following output:

    Since the length of the list that was passed to the assert statement was zero, the condition became false. As a result, assert aborted the execution of the program and displayed the AssertionError message.

  2. In this example, we’ll provide the assert statement with a condition that will satisfy and pass along an error message as well.
                        
    
    def avg(marks):
        assert len(marks) != 0,"List is empty."
        return sum(marks)/len(marks)
    
    mark2 = [55,88,78,90,79]
    print("Average of mark2:",avg(mark2))
    
    mark1 = []
    print("Average of mark1:",avg(mark1))

    Now, when we run this code, the output will look something like this:

                        

    Average of mark2: 78.0
    AssertionError: List is empty.

    In this case, the assert statement was provided with a non-empty list in the form of mark2. Along with it, an empty list was also provided to the avg() function in the form of mark1. As the condition was satisfied for mark2, we got the desired output. From then on, it proceeded to execute mark1. However, as the condition failed to hold true for mark1, we ended up getting the AssertionError message. But because this time we had already passed on an error message as an argument to the assert statement, it displayed that particular error message along with AssertionError.

  3. In this example we’ll consider a function that converts a temperature reading from degrees Kelvin to degrees Fahrenheit. As zero degrees is the lowest possible value for Kelvin scale, the program will stop running upon encountering negative temperature readings.
                        
    
    def KelvinToFahrenheit(Temperature):
       assert (Temperature >= 0),"Colder than absolute zero!"
       return ((Temperature-273)*1.8)+32
    
    print KelvinToFahrenheit(273)
    print int(KelvinToFahrenheit(505.78))
    print KelvinToFahrenheit(-5)

    The output of this code block looks something like this:

                        

    32.0
    451
    Traceback (most recent call last):
       File "test.py", line 9, in 
          print KelvinToFahrenheit(-5)
       File "test.py", line 4, in KelvinToFahrenheit
          assert (Temperature >= 0),"Colder than absolute zero!"
    AssertionError: Colder than absolute zero!

Assert python 3

  • Assertions are defined as statements that serve the purpose of specifying an indisputable fact within your program.
  • The assert statement can accept both a condition as well as an error message.
  • The main utility of the assert statement is to examine the values and types of the argument, and the output of the function in the program.
  • Assert statement can also be considered as a debugging tool for it halts the execution of the program as soon as it encounters an error.

FAQs on Assert Python

Q. What is assert in Python?
Answer: In python, assertions are regarded as boolean expressions that are primarily employed to check whether the conditions specified in the program return true or not. If the value returned is true, then the program concerns itself with executing the subsequent lines of code. However, if the value returned is false, then the program halts, raises an exception, and throws an error.

Q. How do you assert in Python 3?
Answer: Assertion in Python 3 is carried out with the help of its built-in assert statement

Q. What is assert statement?
Answer: The python assert statement is used to validate the truthfulness of a particular condition within a program. If the condition provided fails to be satisfied, then an AssertionError exception is raised by the statement.

Q. How do you assert true in python?
Answer: If the condition that is passed on to the function is satisfied, then one is able to assert true in Python. 

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.