Python assert

CaupolicanDiaz's avatar
Published Apr 12, 2022Updated Sep 22, 2023
Contribute to Docs

The assert keyword confirms the truthiness of a given statement and is often used to facilitate development, document code, and debug.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

assert some_condition, assert_message

The assert keyword is followed by some_condition to be tested, such as validating a data type or membership within a given container. An optional assert_message can be added that will be printed when the assertion error is raised.

Example

The assert keyword can be used to validate a value (or evaluate some other condition):

fav_color = 'blue'
assert fav_color == 'red'
# Output: AssertionError

Codebyte Example

The following example uses assert to evaluate if 'mud' is within the following list things_that_float:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours