Understand Python Assert Statements for Beginners – Python Tutorial

By | September 26, 2019

Assert statements are convenient ways to insert debugging assertions in python application. In this tutorial, we will introduce how to understand and use it for python beginners.

Python Assert Statement

Python assert syntax

assert <condition>

or

assert <condition>,<error message>

When condition is False, python application will raise an exception, error message will be displayed,  when condition is True, assert statement will do nothing and application will continue to run. It seems like:

if not condition:
    print(error message)
    return

How to use assert?

Python assert statements are often used to check the condition whether python application run or not.

Here is a python example for how to use assert, in some applications, we need size of  inputs and targets are the same, if their size are different, python function will not run.

So we can do:

def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
    assert len(inputs) == len(targets),"inputs and target is not the same"

Of course, we also can use if statement to do it.

def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
    if len(inputs) != len(targets):
        print("inputs and target is not the same")
        return

Leave a Reply

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