Assertions in Python
An assert statement checks that a condition is true, and if it isn't, immediately raises an AssertionError — a lightweight way to state "this should always be true at this point in the code," catching bugs early rather than letting incorrect assumptions silently cause problems further down the line. Assertions are meant for catching a programmer's own logic errors during development, not for validating external, untrusted input.
assert condition checks and moves on
Does nothing at all if condition is true.
A false condition raises AssertionError
Immediately, halting execution right there.
A message can be added
assert condition, "message" shows a descriptive message alongside the error.
Assertions can be globally disabled
Running Python with the -O flag strips them out entirely.
So they suit development, not user input
raise and proper exception handling are the right tool for validating real, external input instead.
def calculate_discount(price, percent): assert 0 <= percent <= 100, "Percent must be between 0 and 100" return price * (1 - percent / 100) print(calculate_discount(100, 20))print(calculate_discount(100, 150))Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.