Python assert keyword

Example

Test if the condition returns True:

x = "hello"
# If the condition returns True, nothing will happen:
assert x == "hello"
# If the condition returns False, it will raise an AssertionError:
assert x == "goodbye"

Run Example

Definition and Usage

The assert keyword is used when debugging code.

The assert keyword allows you to test if the condition in the code returns True, otherwise, the program will raise an AssertionError.

You can write a message that is output when the code returns False, see the following example.

More Examples

Example

If the condition is False, write a message:

x = "hello"
# How to conditionally return False, raise AssertionError:
assert x == "goodbye", "x should be 'hello'"

Run Example