assert statements are used for debugging Python programs. The assert statements checks if a condition is
true. If the condition is
assert will stop the program with an optional message. Assert statements should not be used as a functional part of the program, as they can be disabled by the compiler.
Debugging is a crucial part of programming in any language. When debugging programs in Python, there may be times when you want to test for a certain condition and, if that condition is not met, for the program to return an error. That way, you know what to fix in your code.
That’s where the Python assert keyword comes in. The assert statement is a tool that is used to test for a particular condition in Python. It is commonly used during debugging.
This Python tutorial will explore the importance of assertion, how to use the assert statement, and a few examples of using the assert expression in a program.
Assertion in Python
The assert statement is used to test for conditions in Python and fix bugs more quickly. If the condition you are testing with the assert statement evaluates to
True, the program will continue to execute. If the assertion evaluates to False, the program will raise an AssertionError (+/- an optional message).
Assertions are used to identify and remove certain conditions when code is run. For instance, if you are running an operation on a list that will change the list’s values, you may want to use an assertion first to ensure certain conditions are met before the list is changed.
Assertions should not be used in place of program errors such a SyntaxError or a NameError. If you’re looking to test a block of code, using “try … except” would be more appropriate. But if you want to check for a certain condition in your code, an assert statement may be more useful.
It’s worth noting that assertions should be used sparingly and only during debugging. This is important for two reasons.
First, assertions help developers find the cause of a bug before it impacts other code. Assertions do not raise just any error in a program—they have to be defined by the developer.
Second, Python interpreter users can disable assertion statements. Therefore, a number of problems can arise if you rely on assertions too heavily for error handling and a user disables assertions. This also means that you should never use assertions to validate data outside of a development environment because disabling them could have a significant impact on how your program runs.
Python Assert Statements
In Python, assert statements are Boolean expressions that check whether a condition is true. If a condition evaluates to
True, a program will keep running; if it is false, the program will return an AssertionError and will stop executing.
assert is a keyword. It uses the following syntax:
assert condition, message
Here are the two parameters assert can take in:
- condition: the condition for which you want to test (required)
- message: the message you want to display if the assert statement is executed (optional)
Let’s use an example to illustrate the assert keyword in action. Say that we are creating a program that calculates whether a student passed or failed a certain test. A grade of 52 or higher is considered a pass, while any grade lower than 52 is considered a fail.
Before we calculate whether the grades are passes or fails, we want to make sure that we have inserted a user’s data into the program (which means the student’s grade is not 0, in the below example). Otherwise, our program may say that a user failed the test even though the data is not present.
We could create this program using the following code:
student_grades = [57, 74, 49, 0, 87, 66, 89] for g in student_grades: assert student_grades[g] != 0 if student_grades[g] >= 52: print('This student passed.') else: print('This student failed.') print('Program complete')
When we run our code, the program returns the following output:
This student passed. This student passed. This student failed. ... assert student_grades[g] != 0 AssertionError
Let’s break down our code. On the first line, we declare a list of student grades. Then, we create a
for loop that iterates through the list of student grades. This for loop contains an assert statement that will raise an error if the statement
student_grades[g] != 0 evaluates to
False. In other words, if a student’s grade is 0, the program will return an AssertionError.
Then, we define an
if statement that prints a message if a student scored 52 or higher on the test (
This student passed.), and a different message if a student scored less than 52 (
This student failed.). Finally, our program prints out
Program complete to the console.
As you can see, our program started going through the list of student grades and calculating whether they passed or failed the test. However, when our program reached the fourth value in our list, it raised an AssertionError. This is because our student grade was equal to 0.
Remember, we wanted to make sure that each student’s numerical grade was present before a student’s grade was calculated (if it was not, 0 would be written in place of their numerical grade).
This would allow us to make sure that we do not give a student an incorrect grade—which is likely because this program is still in testing and we are not finished with our work. (If this were a final program, we would want to use a more robust error-handling method than assert. But, for the purposes of debugging, assert is acceptable.)
Now, let’s say that we want to include a custom error message in our program. If a user’s grade is equal to
, we want an error to be raised that says
Student grade is 0.. This error will make it clear to us, the developers, what problem our program encountered.
Here’s the code we would use to add an error message to our above code:
... assert student_grades[g] != 0, "Student grade is 0." if student_grades[g] >= 52: print('This student passed.') else: print('This student failed.') …
Now, when we run our program, we get the following result:
This student passed. This student passed. This student failed. … AssertionError: Student grade is 0.
As you can see, the program still raised an AssertionError, but this time it displayed an additional error message that we defined in our code. The additional message can help the developer better understand the problems in their program, which can make debugging more efficient.
Python assertions are a useful debugging tool that can help you write more maintainable code. They make it easier to test for certain conditions in your code. That being said, we suggest you use Python assertions sparingly. Since users can disable assertions, we also suggest you never use them to perform tasks such as data validation.
This guide explored the usefulness and limitations of the Python assert keyword and how to use it. In addition, we discussed an example of the assert keyword in use. We also covered how to define custom error messages using assert.
Knowing how to use the assert statement is a good skill to have. Learning it is another step on your journey toward becoming a Python expert!
Python is a versatile programming language used in many professional applications. Download the free Career Karma app to learn about careers in Python and how you can start your journey to a new career in tech in only 21 days.