Python assert keyword is used (in the debugging tool) while debugging programs that test a condition. The assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError.
assert <condition>
Or
assert <condition>,<error message>
Python assert keyword
A simple example code test is if a condition in code returns True, if not, the program will raise an AssertionError.
x = "hello"
# if True, then nothing happens:
assert x == "hello"
# if False, AssertionError is raised:
assert x == "goodbye"
Output:
Using assert without Error Message
def avg(marks):
assert len(marks) != 0
return sum(marks) / len(marks)
mark1 = []
print("Average of mark1:", avg(mark1))
Using assert with an error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Do comment if you have any doubts or suggestions on this Python Keyword topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.