×

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

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

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

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

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

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.