PythonSyntax and keywords
assert
Checks an assumption in the code and raises AssertionError when it does not hold.
Example
#Python
def average(values):
assert len(values) > 0, "The list cannot be empty"
return sum(values) / len(values)
print(average([80, 90]))
try:
average([])
except AssertionError as error:
print("AssertionError:", error)Resultsaved result, you can check it
85.0
AssertionError: The list cannot be empty
Definition and usage
#The assert condition, message statement checks whether the condition is true. If not, it raises an AssertionError with the given message. It is a way to write down, right in the code, assumptions that should always hold.
Assertions are the foundation of tests in the pytest library: every test is a function that checks results with assert.
Do not use assert to validate data from a user. Python run with the optimization flag (-O) skips all assertions, so that kind of validation could simply disappear. Ordinary conditions and raise are the right tool for that.
Syntax
#Syntax
assert condition, "message"Good practices
#- Use
assertin tests and to check a programmer’s assumptions, not to validate input data. - An assertion message should say which assumption was broken.
Related entries
#Spotted a mistake or missing an example? Write to us.