Python Assert

Python Assert will throw an error if a conditional does NOT equal True. This is most commonly used when debugging your code.

x = 5
assert x==5

Remember that a conditional is denoted by the double equals sign “==”

It is roughly similar to:

if not condition:
    raise AssertionError()

Let’s take a look at a python assert code sample

Python Assert

Assert helps you with debugging. If a conditional does not come back as True, then an AssertionError will be thrown.

In [2]:
x = "Fall Colors"
In [4]:
assert x == "Fall Colors"

# Nothing happens
In [6]:
assert x == "Spring Rain"

# AssertionError is thrown
AssertionError                            Traceback (most recent call last)
<ipython-input-6-990283d4cfbb> in <module>
----> 1 assert x == "Spring Rain"
      3 # AssertionError is thrown


Link to code above

Check out more Python Vocabulary on our Glossary Page