Ads by ProfitSence

Use of assert in Python.

Last Updated on Wednesday 5th Oct 2022


Python has built-in assert statement to use assertion condition in the program

Assert, a condition that should not be False.

  • If the condition is False, then an AssertionError error is raised along with the exception message text.
  • Expression can be any string or anything that produces a string.

Syntax of Assert

					assert condition, expression


Some Examples

					a = 11

assert(a < 10 ), 'a should not exceed 10'



					AssertionError: a should not exceed 10


In the above example, the assert condition, x > 10 evalutes to be False, and so it will raise the AssertionError with the specified message 'a should not exceed 10'

					import sys
assert ('linux' in sys. platform), 'This code runs on Linux only.'



					AssertionError: This code runs on Linux only.


When Use Assert Statement

  • To inform developers about unrecoverable errors in a program.
  • Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors.

Don't Use Asserts for Data Validation

  • Asserts can be turned off globally in the Python interpreter.For Docs Link
  • When you pass a tuple as the first argument in an assert statement.
  • The assertion always evaluates as true and therefore never fails.

With Simple assert, You can verify that

  • A condition has been met
  • Throw exceptions if it hasn't
python assert
assert python
asserts in python
import assert python
python how to use assert
assert in python
asserts python
python assert in
python assert statement
python assert usage