Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: March 13, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Are you a programmer? If so, debugging is an essential skill, irrespective of the language you’re coding in. In this article, you will learn how to use the assert statement in Python for effective debugging.

When you’re working on a project, you’ll define multiple modules. This includes functions, class definitions, and more. And you’ll likely run into errors or unexpected results because of a bug in the implementation. Assert statements are helpful in debugging such code.

In this tutorial, we’ll learn the syntax to use the assert statement followed by code examples to see it in action. We’ll also see what assertion errors are and how we can use them to fix the errors in code during development.

Let’s begin!

How to Use the Assert Statement in Python

We’ll learn the syntax to use the assert statement, then proceed to code some examples.

Syntax of the Assert Statement

Let’s start with the syntax to use the assert statement in Python:

assert expression, message


  • expression is any valid Python expression to be evaluated. This can be a condition on the value of variable, truth value of variable, return value from a function, and more.
  • So long as the expression evaluates to True, the assert statement does not throw an error or return anything. This indicates that the program works as expected.
  • If the expression is no longer True, an AssertionError exception is raised.
  • message is an optional string. You can specify a message that gets displayed in the trace back whenever an AssertionError exception is raised.

Next, let’s proceed to code a few examples where the assert statement can help us write cleaner and bug-free code.

You can find the code examples used in this tutorial in this GitHub gist.

Python’s Assert Statement Examples


Consider the following example. Say you have a discount variable in your code. But you’d like its value to be always less than or equal to the max_discount.

To check that you accidentally don’t set the discount variable to a value, you can add an assertion. The expression to evaluate is: discount <= max_discount.

>>> max_discount = 50
>>> discount = 20
>>> assert discount <= max_discount

Here, discount (20) is less than max_discount (50). So the assert statement does not throw any error.

The AssertionError Exception

If the discount variable is set to a value greater than max_discount, an AssertionError exception is raised.

>>> discount = 75
>>> assert discount <= max_discount
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

We know that the assert statement also allows us to specify an optional message string.

Let’s also use a message string that gives a more descriptive diagnostic info. To the assert statement, let’s add a Python f-string that also contains the values of discount and max_discount.

>>> assert discount <= max_discount, f"discount should be at most {max_discount}; got discount = {discount}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: discount should be at most 50; got discount = 75

As seen in the output cell above, the AssertionError exception now includes the values of the discount and max_discount variables.

Debugging and Testing Python Functions with Assert

When defining functions, you may sometimes inadvertently introduce bugs (logical errors) that will prevent your function from working as intended.


Let’s take an example. Suppose there’s a test in a class and the students are given a chance to attempt a bonus question. Any student who attempts the bonus question will get 10 additional marks in the test. 😄

Consider the following function get_final_score:

  • It takes in a current score, score, and a Boolean bonus
  • If a student has answered the bonus question, the Boolean bonus is True, and they get 10 points more than their current score.
  • The function then returns the final score.
def get_final_score(score,bonus):
    if bonus:
        score += 10
    return score

Let’s make a few calls to the function. We see that for scores of 34 and 40 with bonus set to True and False, the final scores are 44 and 40, respectively.

# 44
# 40

However, the maximum points on the test is, say, 50. So if a student scores 49 and has also answered the bonus question, the function get_final_score will happily compute the final score to be 59.

# 59

Technically, it’s possible. But let us assume that a student cannot score more than the maximum possible points for the test. 🙂

So let’s initialize a max_score variable. And capture the returned score from the function in the final_score variable.

Subsequently we add an assertion that checks if the final_score is less than the max_score.

def get_final_score(score,bonus):
    if bonus:
        score += 10
    return score

final_score = get_final_score(47,True)
max_score = 50

assert final_score <= max_score

We now get an AssertionError exception for the function call get_final_score(47,True):

Traceback (most recent call last):
  File "", line 17, in <module>
    assert final_score <= max_score

Now we add a descriptive f-string to the Python assert statement:

assert final_score <= max_score,f"final_score should be at most {max_score}; got {final_score}"
Traceback (most recent call last):
  File "", line 17, in <module>
    assert final_score <= max_score,f"final_score should be at most {max_score}; got {final_score}"
AssertionError: final_score should be at most 50; got 57

Modifying the Function

Let’s go back and modify the definition of the get_final_score function to fix the unexpected behavior:

  • The function get_final_score also takes max_score as a parameter.
  • We check if bonus is True. If True, we add 10 points to the score variable.
  • Then, we check if score is greater than max_score. If so, we return max_score.
  • Otherwise, we return score.

We’ve now ensured that the final score is always less than or equal to max_score.

def get_final_score(score,bonus,max_score):
    if bonus:
        score += 10
    if score > max_score:
        return max_score
    return score

As a quick exercise, write a few assertions to confirm that the function now works as expected.

A Note on AssertionError Exception

Though an AssertionError exception occurs when the expression evaluates to False, we should remember to not handle such errors as exceptions. Meaning we should not do something like this:

    <doing this>
except AssertionError:
    <do this>

In the previous example on get_final_score, we used the assertion to check if final_score is less than max_score. Then we modified the function definition such that there are no assertion errors.

That’s what assertions are for. They are sanity checks for code, and help in writing cleaner code. Exception handling, on the other hand, is to anticipate and handle unexpected errors at runtime. These often include invalid input types and values.

To sum up, you should use Python assert statement for effective debugging and not handle AssertionErrors as exceptions.


This tutorial helped you understand how to use assert statement in Python. Here’s a summary of what you’ve learned:

  • Python assert statements (assertions) take the form assert expression. This checks if the expression is True. If it does not evaluate to True, an AssertionError exception is raised.
  • You can also use the assert with the syntax assert expression, message. This will print out the message string whenever an AssertionError exception occurs.
  • You should remember not to implement exception handling to handle assertion errors. And use assertions as a helpful debugging tool for sanity checks of your code.

As a developer, assertions help you with debugging. To ensure all the individual components (modules) of the project work as expected, you can learn how to write unit tests in Python.

Next, check out this list of beginner Python projects you can work on.

  • Bala Priya C
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder