Nearby lessons

85 of 159

Python - Assertions

📌 What You Will Learn
  • Understand why assert is often better than print() for debugging
  • Learn the two forms of the assert statement - simple and augmented
  • Know that assert raises AssertionError when its condition evaluates to False
  • Use assertions to detect bugs in functions during development
  • Distinguish when to use assertions versus exception handling

Introduction to Assertions

The process of identifying and fixing bugs in a program is called Debugging.

A very common way of debugging is to use the print() statement. However, after fixing the bug, we must delete the extra print() statements that were added for debugging.

If we forget to delete them, these statements keep executing at runtime, which creates performance problems and disturbs the console output.

The assert Statement

To overcome the problem of print() debugging, Python provides the assert statement.

After fixing a bug, we are not required to delete the assert statements — based on our requirement, we can enable or disable them.

Purpose of Assertions

The main purpose of assertions is to perform debugging.

Debugging is usually performed in development or test environments, but not in the production environment.

Hence, the assertions concept is applicable only for development and test environments, but not for the production environment.

Syntax of assert

🐍Code Cell
1assert conditional_expression
Output
No output captured.

How Does assert Work?

The conditional_expression is evaluated by the Python interpreter.

  • If the condition is True, the program continues normally.
  • If the condition is False, the program is terminated by raising an AssertionError.

By seeing the AssertionError, the programmer can analyze the code and fix the problem.

Types of assert Statements

Type Syntax
Simple Version assert conditional_expression
Augmented Version assert conditional_expression, message

Simple Version

In the simple version, only a conditional_expression is given. If the condition is False, an AssertionError is raised without any message.

🐍Code Cell
1x = 10
2 
3assert x > 100
Output
AssertionError

Augmented Version

In the augmented version, a message is also provided along with the conditional_expression. If the condition is False, an AssertionError is raised and the message is displayed.

🐍Code Cell
1x = 10
2 
3assert x > 100, "x must be greater than 100"
Output
AssertionError: x must be greater than 100

Example - Program with a Bug

Write a function that returns the square of a number, and verify it using assert statements. Initially, the function is written incorrectly using the exponent operator:

🐍Code Cell
1def squareIt(x):
2 return x**x
3 
4assert squareIt(2) == 4, "The square of 2 should be 4"
5assert squareIt(3) == 9, "The square of 3 should be 9"
6assert squareIt(4) == 16, "The square of 4 should be 16"
7print(squareIt(2))
8print(squareIt(3))
9print(squareIt(4))
Output
AssertionError: The square of 3 should be 9

Explanation

Here, squareIt(x) uses x**x (x raised to the power x) instead of x*x (x multiplied by x).

  • squareIt(2) returns 2**2 = 4 → the first assertion passes.
  • squareIt(3) returns 3**3 = 27 → the second assertion fails.

Because the second condition is False, the program terminates with AssertionError: The square of 3 should be 9.

The assert statement helped us detect the bug in the function without adding extra print() statements.

Corrected Program

After fixing the function to use x*x, all the assertions pass:

🐍Code Cell
1def squareIt(x):
2 return x*x
3 
4assert squareIt(2) == 4, "The square of 2 should be 4"
5assert squareIt(3) == 9, "The square of 3 should be 9"
6assert squareIt(4) == 16, "The square of 4 should be 16"
7print(squareIt(2))
8print(squareIt(3))
9print(squareIt(4))
Output
4
9
16

Exception Handling vs Assertions

Assertions and Exception Handling are used for different purposes:

Aspect Assertions Exception Handling
Purpose To alert the programmer to resolve development-time errors. To handle runtime errors.
When It Occurs Used for debugging internal program logic. Used to handle errors that occur during program execution.
Example assert statement try-except blocks
📝 Key Takeaways
  • assert stops the program with an AssertionError when the condition is False
  • Assertions are meant for development and test environments, not production
  • The augmented form - assert condition, message - attaches a custom message to the error
  • assert statements do not have to be removed after fixing a bug - they can be enabled or disabled
  • assert catches internal logic bugs, while try/except handles runtime errors

🧠 Test Your Knowledge

5 Questions
Progress: 0 / 5