×

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

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

XXhash Python

Python: 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 is said...

6 minutes read.

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 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.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

Python Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.