×

Python Assert

Python Assert

Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an Assertion Error.

It is also a debugging tool, which interrupts the program when an error occurred in the program and shows on which line the error has occurred. The syntax is given below:

assert 
or
assert   

Flow diagram

Python Assert

In the above flow diagram, Assertions are Boolean expressions that check if the given condition returns true or false. If it returns true, the program does nothing and moves to the next line of code. However, if it returns false, the program stops and shows an error.

Consider the below example, where we declare a function to divide two numbers.

Example-1 Using assert without error message

def fun(a,b):
    assert b!=0
    c= a/b
    return c

print(fun(20,10))
print(fun(20,0))

Output:

line 2, in fun
    2.0
assert b!=0
AssertionError 

In the above program, when we call the function with passing argument 20 and 10, it gives 2.0 as a result. If we pass b as Zero, then it violates the condition and assert statement raise an Assertion error.

Example-2  Using assert with error message

def avg(numbers):
    assert len(numbers)!=0
    sum = 0
    for temp in numbers:
        sum = temp+sum
    return sum/len(numbers)

numbers = [53,56,85,90,45,95]
print("The average is:",avg(numbers))

numbers1 =[] # An Empty list
print("The average is:",avg(numbers1))

Output:

The average is: 70.67
line 2, in avg
        assert len(numbers)!=0,"List is empty"
AssertionError: List is empty 

We have passed numbers list and number1 as a non-empty list that’s why we got the output for the numbers and got AssertionError: List is empty for a non-empty list.

The assertion is used for:

  • Testing code.
  • Checking output of functions.
  • As a debugger to stop when an error occurs.
  • In checking values of arguments.

Key points to remember

  • assert statement accepts an expression and an optional message.
  • assert statement is used as a debugging tool.
  • assert statement is used to check types, values of the argument, and the output of the function.
  • Assertions are the condition or Boolean expression which is always supposed to be true in the code.

Related Topics

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.