How To Use Assert In Python3

Assertions are an excellent tool for debugging and testing your Python code. When using the assert statement, Python will raise an exception if the specified condition is not True.

This allows you to immediately detect any potential problems, ensuring that the correct values or conditions are met before your code proceeds. In this tutorial, you will learn how to use the assert statement in Python 3, with examples of string manipulation, list manipulation, and mathematical operations.

Step 1: The Basic Syntax of Assert

The basic syntax of assert is as follows:

The expression represents the condition that must evaluate to True. If the expression evaluates to False, Python raises an AssertionError exception with an optional message.

Here’s an example:

Step 2: Using Assert for String Manipulation

Consider the following function that ensures a string only has uppercase characters:

If you call the function with an uppercase string, it will return the string; otherwise, it will raise an AssertionError.

Example:

HELLO

Now, let’s try it with lowercase characters:

This code will raise an AssertionError with the message “String should be in uppercase.”

Step 3: Using Assert for List Manipulation

Assertions in list manipulation can be useful to check if the required condition is met for all elements within the list. Here’s an example demonstrating the use of assert to check if all elements in a list are positive integers:

[1, 2, 3, 4, 5]

Now, let’s test with negative integers:

This code will raise an AssertionError with the message “Element -4 should be positive.”

Step 4: Using Assert for Mathematical Operations

You can use assert to check the results of mathematical operations. Consider the following example that checks if a number is even:

12

If you now test an odd number:

This line will raise an AssertionError with the message “13 should be even.”

Full code:

Conclusion

In this tutorial, you learned about the Python assert statement and its usage in various contexts such as string manipulation, list manipulation, and mathematical operations.

While useful for debugging and testing, it is important to note that assertions should not be used as a security feature or to validate input data, as they can be disabled globally in the interpreter with the ‘-O’ (optimize) command-line switch.

Therefore, it is recommended to use assert primarily during the development and testing phases of your project.