RSVP here for our first hackathon! Free prizes, the kickoff is 8 AM PST Jan 17th

Python Assert Statement, How to Test a Condition

A learning path to your next coding job

  1. Join the Qvault community and share your career goals
  2. We'll help you find the knowledge gaps holding you back
  3. Complete recommended courses and projects
  4. Find your next opportunity with a newly polished resume

Our courses include but are not limited to

  • Golang, Python, JavaScript
  • Algorithms, data structures, cryptography
  • Graphics and functional programming

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
Code language: Python (python)

tl;dr

  • Assertions are simply boolean expressions that raise exceptions if their condition is False
  • The assert statement is the built-in syntax for assertions in Python
  • Developers often use assert to do type checking, and input/output validation for function signatures
  • The assert statement is used for debugging purposes

Anatomy of an assert statement in Python

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

assert condition [, error_message]
Code language: Python (python)

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

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!"
Code language: Python (python)

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.

test in production meme

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.

Trying to find your next programming job?

If you are a self-taught developer having trouble finding your first programming job, we've got your back! We have the learning resources and tight-knit dev community that you need to land the coding job you've been looking for. To get started, create a free account and join our Discord community.

Have questions or feedback?

If we've made a mistake in the article, please let us know so we can get it corrected!