0
0
Pythonprogramming~5 mins

Assert statement usage in Python

Choose your learning style9 modes available
Introduction

An assert statement helps check if something is true while your program runs. If it is not true, the program stops and shows an error. This helps find mistakes early.

To check if a number is positive before doing math with it.
To make sure a list is not empty before accessing its items.
To verify a function input is the right type or value.
To catch unexpected situations during development.
To test assumptions in your code without writing extra checks.
Syntax
Python
assert condition, "error message"

The condition is what you expect to be true.

The error message is optional but helps explain the problem if the assertion fails.

Examples
Check that x is greater than zero. If not, the program stops.
Python
assert x > 0
Check the list is not empty. If it is, show the message.
Python
assert len(my_list) > 0, "List should not be empty"
Check that name is a string type.
Python
assert isinstance(name, str), "Name must be a string"
Sample Program

This program defines a function to divide two numbers. It uses assert to stop if the second number is zero, avoiding a crash later.

Python
def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

print(divide(10, 2))
print(divide(5, 0))
OutputSuccess
Important Notes

Assertions are mainly for debugging and testing, not for handling user errors in production.

You can disable all assertions when running Python with the -O option.

Summary

Assert checks if something is true and stops the program if not.

It helps catch bugs early by verifying assumptions.

Use clear messages to explain what went wrong.