Home >>Python Keywords >Python assert Keyword

Python assert Keyword

Python assert Keyword

Python assert keyword is used for the debugging of the codes. It lets you test if a condition in your code returns True, if not then the program will raise an AssertionError.

Here is an example of Python assert keyword:

x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye"

Output:
Traceback (most recent call last):
File "demo.py", line 5, in assert x == "goodbye"
AssertionError
Example 2:

x = "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye", "x should be 'hello'"

Output:
Traceback (most recent call last):
File "demo.py", line 4, in assert x == "goodbye", "x should be 'hello'"
AssertionError: x should be 'hello'

No Sidebar ads