Don't spend $10k on a bootcamp. Try our back-end career path first.
Back home

Python Assert Statement, How to Test a Condition

By Lane Wagner on Dec 13, 2021

In Python, an assertion is a statement that confirms something about the state of your program. For example, if you write a createUser function and you are sure that the user needs to be older than 18, you assert that the age field is greater than or equal to 18. You can think of an assert statement like a unit test that is performed at runtime.

def createUser(user):
  assert user.age >= 18

tl;dr

Anatomy of an assert statement in Python

Python has a built-in assert statement, and its syntax is as follows.

assert condition [, error_message]

If the {condition} is false, an AssertionError is raised. If the optional second parameter, error_message was set, then that error message is used.

A simple path to your career in back-end development

The pace of Boot.dev's JavaScript, Python and Go courses has been perfect for me. The diverse community in Discord is a blast, and other members are quick to help out with detailed answers and explanations.

- Daniel Gerep from Cassia, Brasil

Catching an assertion error

You can catch an assertion error just like you would any other error in Python.

age = 17
try:
    assert age >= 18, "too young!"
except Exception as e:
    print(e)
# prints: "too young!"

Don’t use the assert statement in production

The assert statement is a fantastic tool for debugging code and writing tests. You should probably not use an assert statement in a production environment. You should be checking your code for unexpected behavior before you deploy it.

Don’t use parenthesis for the assert parameters

Do not use parentheses to call assert as if it were a normal function. Asser is a statement, not a function. When you call assert(condition,message), you execute the assert statement with a tuple (condition,message) as the condition, and no actual message.

Learn back-end without spending $10,000+ on a bootcamp

Related Reading