Python Assert Keyword
The assert keyword in Python serves as a debugging mechanism that evaluates a specified condition. Assertions fundamentally represent assumptions that confidently affirm a fact within the code. For instance, when developing a function for division, it is crucial to ensure that the divisor does not equal zero, prompting you to assert that the divisor is not zero.
A Boolean expression serves to assess a condition or expression, determining whether it evaluates to true or false. When the evaluation results in true, the program continues execution without taking any action and proceeds to the subsequent line of code. Conversely, if the evaluation yields false, an AssertionError exception is triggered, which may include an optional message detailing the error.
The primary function of assertions is to notify developers of non-recoverable errors within the application, such as "file not found." It is accurate to describe assertions as internal self-verification mechanisms for the software. This is crucial for testing or quality assurance in any domain of application development. Below is the syntax for the assert keyword.
Syntax of the Assert Keyword
Assert keyword has the following syntax:
assert condition, error_message(optional)
Why Assertion is used in Python?
This is a debugging utility, whose main function is to evaluate a specific condition. When it determines that the condition evaluates to true, it proceeds to the subsequent line of code. Conversely, if the condition is false, it halts all operations and raises an error. This tool identifies the location of the error within the code.
Where Assertion is used in Python?
- Checking the outputs of the functions.
- Used for testing the code.
- In checking the values of arguments.Checking the valid input.
Python Program to Demonstrate assert Keyword
This illustration demonstrates the functionality of the assert statement accompanied by an error message in Python.
def avg(scores):
assert len(scores) != 0,"The List is empty."
return sum(scores)/len(scores)
scores2 = [67,59,86,75,92]
print("The Average of scores2:",avg(scores2))
scores1 = []
print("The Average of scores1:",avg(scores1))
Output:
The Average of scores2: 75.8
AssertionError: The List is empty.
Explanation:
In the preceding example, we provided a populated list named scores2 alongside an empty list referred to as scores1 to the avg function. The function successfully returned a result for the scores2 list. However, it subsequently raised an error: AssertionError: List is empty. The assertion condition is met by the scores2 list, allowing the program to execute further. Conversely, scores1 fails to meet this condition, resulting in an AssertionError.
Assertion Example for Divide by Zero Error
Consider an illustration that demonstrates the "Divide by 0 error" within the console.
# initializing number
x = 7
y = 0
# It uses assert to check for 0
print ("x / y value is : ")
assert y != 0, "Divide by 0 error"
print (x / y)
Output:
x / y value is :
Runtime Exception:
Traceback (most recent call last):
File "main.py", line 6, in <module>
assert y != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
Explanation:
In the preceding example, an integer variable has been set up: x=7 and y=0. We attempt to display the outcome of x/y. However, the Python interpreter raised a Runtime Exception due to the assert keyword identifying the divisor as zero, subsequently showing "Divide by 0 error" in the console.