Back to Python
2026-03-205 min read

Python Asserts

Learn Python Asserts step by step with clear examples and exercises.

Title: Python Assert Statement - A full guide for Debugging and Error Handling

Why This Matters

In software development, it is crucial to ensure that our code runs smoothly and produces the expected results. However, due to various reasons such as logical errors, incorrect data input, or unforeseen conditions, our code might sometimes behave unexpectedly. To handle these situations, Python provides a powerful tool called the assert statement, which helps in debugging and error handling. In this lesson, we will delve into understanding what assert statements are, how to use them effectively, common mistakes to avoid, and practice questions to test your knowledge.

Prerequisites

Before diving into the core concept of Python assert statements, it is essential to have a good grasp of the following topics:

  • Basic Python syntax and data types (variables, operators, control structures)
  • Functions in Python
  • Error handling using exceptions (try, except)
  • Understanding recursion and its applications

Core Concept

What are Assert Statements?

Assert statements are used to test conditions within your code. If the condition is not met, an AssertionError exception is raised, which can help you identify and fix logical errors or inconsistencies in your code. The assert statement checks a condition at runtime, and if the condition evaluates to False, it raises an AssertionError along with a user-defined error message.

Syntax and Usage

The basic syntax of an assert statement is as follows:

assert condition, message

Here, condition is the expression being tested, and message (optional) is an error message that will be displayed if the condition evaluates to False. If the condition is True, the assert statement does nothing, and the program continues execution as usual.

Example

Let's consider a simple example where we want to ensure that a user-provided age is greater than or equal to 18:

def check_age(age):
assert age >= 18, f"The provided age {age} must be greater than or equal to 18"

check_age(20) # No error since the condition is True
check_age(17) # Raises an AssertionError with the specified message

In this example, we have a function check_age() that checks if the provided age is greater than or equal to 18. If not, it raises an AssertionError with a user-defined error message.

Advanced Example - Factorial Calculation using Recursion and Assert Statements

Consider a function that calculates the factorial of a number using recursion:

def factorial(n):
assert n >= 0, f"Factorial cannot be calculated for non-nonative numbers. Given number: {n}"
if n == 0 or n == 1:
return 1
else:
result = n * factorial(n - 1)
assert result == factorial_check(n), f"Calculated factorial value does not match the expected value for number {n}"
return result

def factorial_check(n):
if n <= 1:
return 1
else:
return n * factorial_check(n - 1)

In this example, we have a function factorial() that calculates the factorial of a number using recursion. We also have an auxiliary function factorial_check() that calculates the expected factorial value for a given number. The assert statement checks if the calculated factorial value matches the expected one. If not, it raises an AssertionError with a user-defined error message.

Worked Example

In this section, we will walk through a more complex example that demonstrates the use of assert statements for debugging and error handling.

Consider a function that validates a credit card number using Luhn's algorithm:

def is_valid_credit_card(number):
assert isinstance(number, int), "Credit card number must be an integer"
if len(str(number)) != 16:
raise ValueError("Invalid credit card number length")

odd_sum = 0
even_sum = 0
for i in range(len(str(number))):
digit = int(str(number)[i])
if i % 2 == 0:
even_sum += double_digit_sum(digit)
else:
odd_sum += digit

return odd_sum + even_sum == 0

def double_digit_sum(number):
assert 0 <= number <= 9, f"Invalid double digit value. Given number: {number}"
if number > 4 and number < 10:
return number + (10 - number) % 10
else:
return number

In this example, we have a function is_valid_credit_card() that checks if a given credit card number is valid using Luhn's algorithm. The assert statements are used to ensure that the input is an integer and that the length of the credit card number is 16. Additionally, the double_digit_sum() function uses assert statements to validate double digit values within the acceptable range.

Common Mistakes

  1. ### Forgetting the Comma (,)

Incorrect:

assert condition message

Correct:

assert condition, message
  1. ### Not providing an error message

While it is optional to provide an error message, doing so can help you understand the cause of the error more easily.

  1. ### Using assert statements for flow control

Assert statements are not meant for controlling the flow of your program. Instead, they should be used for testing conditions that are expected to hold true during normal execution.

  1. ### Not handling AssertionErrors in production code

In production code, it is generally a good idea to remove assert statements or handle them appropriately since they raise exceptions. You can use try-except blocks to catch and handle AssertionErrors gracefully.

Practice Questions

  1. Write an assert statement that checks if a list contains the number 42. If it does, print "Found 42!" If not, raise an AssertionError with the message "42 not found in the list."
my_list = [1, 2, 3, 4, 5]
assert 42 in my_list, "42 not found in the list"
print("Found 42!")
  1. Write a function that calculates the sum of all numbers in a list. Use assert statements to ensure that the input list only contains integers and is non-empty.
def sum_list(lst):
assert isinstance(lst, list), "Input must be a list"
assert len(lst) > 0, "List cannot be empty"
for num in lst:
assert isinstance(num, int), "All elements in the list must be integers"
return sum(lst)

Test the function with some examples

print("Sum of [1, 2, 3]:", sum_list([1, 2, 3])) # Correct output: 6

print("Sum of ['a', 1, 'b']:", sum_list(['a', 1, 'b'])) # Raises an AssertionError due to the non-integer element

FAQ

Q1. Can I use assert statements in production code?

A1. While it is generally a good idea to remove assert statements from your production code since they raise exceptions, there are cases where you might want to keep them for debugging purposes or to enforce certain conditions that should never be violated. Just make sure to handle the AssertionErrors appropriately in such cases.

Q2. Can I use multiple assert statements within a single function?

A2. Yes, you can have multiple assert statements within a single function. However, keep in mind that if any of the conditions evaluate to False, an AssertionError will be raised immediately, and the rest of the function will not be executed.

Q3. Is it possible to disable assert statements during runtime?

A3. Yes, you can disable assert statements during runtime by setting the PYTHONASSERTS environment variable to 0 or by using a try-except block around the code that contains assert statements. This can be useful for turning off assert checks in production code without modifying the source code directly.

Python Asserts | Python | XQA Learn