Assertions are a powerful tool in Python used to check that conditions hold true while your program runs. By using the assert statement, we can declare that a certain condition must be true at a specific point in our code. If the condition is true, execution continues normally; if it is false, an AssertionError is raised and the program stops (or the error is caught if handled).
This mechanism is especially useful for catching bugs early, validating input values and enforcing invariants in your code.

Syntax
assert condition, error_message
Parameters:
- condition: The boolean expression to check.
- error_message: (Optional) Message to display if the assertion fails.
Examples of assertion
Example 1: Basic Assertion with Error Message
Python
x = 1
y = 0
assert y != 0, "Invalid Operation: Denominator cannot be 0"
print(x / y)
Output :
Traceback (most recent call last):
File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in
assert y!=0, "Invalid Operation" # denominator can't be 0
AssertionError: Invalid Operation
Explanation:
- The code asserts that y is not zero.
- If y is zero, it raises an AssertionError with the message "Invalid Operation: Denominator cannot be 0".
- If the condition were true, the program would proceed to print the result of x / y.
The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message, both the ways are valid.
Example 2: Handling an AssertionError
Assertions can be caught and handled using a try-except block. This is useful when you want to gracefully handle the error and provide custom output.
In Example 1 we have seen how the default exception handler does the work. Now let's dig into handling it manually:
Python
try:
x = 1
y = 0
assert y != 0, "Invalid Operation: Denominator cannot be 0"
print(x / y)
except AssertionError as error:
print(error)
OutputInvalid Operation: Denominator cannot be 0
Explanation:
- The assertion is checked inside a try block.
- If the condition fails (i.e., if y is 0), the exception is caught and the error message is printed.
Practical Application: Testing a Function
Assertions are often used in testing to validate that functions produce the expected results. Consider the following example for solving a quadratic equation.
Example 3: Roots of a Quadratic Equation
Python
import math
def quadratic_roots(a, b, c):
try:
assert a != 0, "Not a quadratic equation: coefficient of x^2 cannot be 0"
D = (b * b - 4 * a * c)
assert D >= 0, "Roots are imaginary"
r1 = (-b + math.sqrt(D)) / (2 * a)
r2 = (-b - math.sqrt(D)) / (2 * a)
print("Roots of the quadratic equation are:", r1, r2)
except AssertionError as error:
print(error)
quadratic_roots(-1, 5, -6) # Expected valid roots
quadratic_roots(1, 1, 6) # Expected error: roots are imaginary
quadratic_roots(2, 12, 18) # Expected valid roots
OutputRoots of the quadratic equation are: 2.0 3.0
Roots are imaginary
Roots of the quadratic equation are: -3.0 -3.0
Explanation:
- The function quadratic_roots computes the roots of a quadratic equation.
- It asserts that a is not zero (ensuring it is indeed quadratic) and that the discriminant D is non-negative.
- If an assertion fails, it prints the corresponding error message instead of crashing abruptly.
Some Other Practical Applications of Assertions:
- Parameter Validation: Ensure function parameters meet specific criteria.
- Type Checking: Confirm that variables are of the expected type.
- Interface Enforcement: Detect improper use of functions or classes by other programmers.
- Testing: Validate outputs and internal states during development.
Similar Reads
Python assert keyword Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn't allow the code to execute further. Assert Keyw
7 min read
Python in Keyword The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.Example:Pythons = "Geeks for geeks" if "for" in s: print("found") else: print("not found")
3 min read
Comparison Operators in Python Python operators can be used with various data types, including numbers, strings, boolean and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters
4 min read
Python unittest - assertIn() function assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container strin
2 min read
is keyword in Python In programming, a keyword is a âreserved wordâ by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
2 min read