#Day26 — Assert Statements in Python and When NOT to use them

Today we will discuss the assert statement in Python.

Rahul Banerjee
Programming Tips

--

Assert statements are a great tool for debugging. Given a boolean condition, they will raise an error if the condition evaluates to False. More specifically, it raises an “AssertionError”. We can also include our custom error messages.

General Syntax

# Without Error message
assert boolean Expression
#With Error message
assert boolean Expression, "Error Message"

Standard If…….else

Let’s assume we have a function that calculates the Mass of an object. The Mass of an object must always be positive. We can have a check to ensure this

def calculate_mass():
# Some stuff to calculate the mass
mass = 10
if mass > 0:
pass
else:
raise Exception()
calculate_mass()

This would work fine in the above case since mass = 10 and is greater than 0. However, if we set the mass to -10, you’d see the following on the console

Traceback (most recent call last):
File "main.py", line 9, in <module>
calculate_mass()
File "main.py", line 7, in calculate_mass
raise Exception()
Exception

--

--