Search⌘ K

Making Assertions

Explore how to use Python's assert statement to validate expressions and trigger errors when conditions fail. Understand adding custom messages and practical applications like error handling in puzzles.

We'll cover the following...

Like many programming languages, Python has an assert statement. Here’s how it works.

Python 3.5
assert 1 + 1 == 2 #①
assert 1 + 1 == 3 #②
#Traceback (most recent call last):
# File "/usercode/__ed_file.py", line 2, in <module>
# assert 1 + 1 == 3 # \u2461
#AssertionError
Python 3.5
assert 2 + 2 == 5, "Only for very large values of 2" #③
#Traceback (most recent call last):
# File "/usercode/__ed_file.py", line 1, in <module>
# assert 2 + 2 == 5, "Only for very large values of 2" #\u2462
#AssertionError: Only for very large values of 2

① The assert statement is followed by any valid Python expression. ...