Learn Python
>>> exception_handling.assertions

Assertions in Python

#concept

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.

#how it works
1

assert condition checks and moves on

Does nothing at all if condition is true.

2

A false condition raises AssertionError

Immediately, halting execution right there.

3

A message can be added

assert condition, "message" shows a descriptive message alongside the error.

4

Assertions can be globally disabled

Running Python with the -O flag strips them out entirely.

5

So they suit development, not user input

raise and proper exception handling are the right tool for validating real, external input instead.

#example
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))
Output
80.0
Traceback (most recent call last):
File "example.py", line 6, in <module>
print(calculate_discount(100, 150))
AssertionError: Percent must be between 0 and 100
1calculate_discount(100, 20) passes the assertion, since 20 genuinely falls between 0 and 100, so the function continues and returns the discounted price.
2calculate_discount(100, 150) fails the assertion, since 150 is outside the valid range — Python immediately raises an AssertionError with the custom message attached.
3Unlike a caught exception, this assertion isn't wrapped in a try/except here, so it stops the program and prints a traceback, exactly as an unhandled exception would.
#use cases
Documenting and checking an assumption a function relies on internally, catching a logic bug immediately if it's ever violated
Sanity-checking intermediate results while developing and debugging a piece of code
Writing simple test assertions to verify a function returns the expected value
Understanding why assertions shouldn't be used to validate user input or handle expected real-world failures, since they can be stripped out entirely

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.