Python assert Keyword

❮ Python Keywords


Example

Test if a condition returns True:

x = "hello"

#if condition returns True, then nothing happens:
assert x == "hello"

#if condition returns False, AssertionError is raised:
assert x == "goodbye"
Try it Yourself »

Definition and Usage

The assert keyword is used when debugging code.

The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.

You can write a message to be written if the code returns False, check the example below.


More Examples

Example

Write a message if the condition is False:

x = "hello"

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

❮ Python Keywords

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.