AssertionError Examples
Short, runnable programs that show python assertionerror in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python AssertionError lesson.
1A guard inside a function
An assert documents what a function assumes about its own inputs and fails loudly during development.
def percent_of(part, whole):
assert whole != 0, "whole must not be 0"
return round(part / whole * 100, 1)
print(percent_of(45, 60))
try:
percent_of(5, 0)
except AssertionError as err:
print("AssertionError:", err)Expected output75.0
AssertionError: whole must not be 0
2Checking types with isinstance
isinstance in an assert catches a wrong type early, before it causes a confusing error further down.
def total_price(prices):
assert isinstance(prices, list), f"expected a list, got {type(prices).__name__}"
return sum(prices)
print(total_price([4, 6.5]))
try:
total_price("4,6.5")
except AssertionError as err:
print("AssertionError:", err)Expected output10.5
AssertionError: expected a list, got str
3Float comparison with isclose
math.isclose compares within a small relative tolerance, which is what you want after floating-point arithmetic.
import math
prices = [19.99, 5.01, 0.10]
total = sum(prices)
print(total == 25.1, math.isclose(total, 25.1))
assert math.isclose(total, 25.1, abs_tol=1e-9)
print("total is correct")Expected outputFalse True
total is correct
4Assert as a tiny test
Before learning a test framework, a few asserts with known answers already catch many bugs.
def initials(name):
return "".join(part[0].upper() for part in name.split())
assert initials("asha rao") == "AR"
assert initials("Kiran") == "K"
assert initials(" maria de souza ") == "MDS"
print("initials() passed 3 checks")Expected outputinitials() passed 3 checks
5Checking an invariant after a calculation
The assert verifies your own logic: a shuffled bill split must still add up to the total.
def split_bill(total_cents, people):
base, extra = divmod(total_cents, people)
shares = [base + (1 if i < extra else 0) for i in range(people)]
assert sum(shares) == total_cents, "shares must add up to the bill"
return shares
print(split_bill(1000, 3))
print(split_bill(999, 3))Expected output[334, 333, 333]
[333, 333, 333]
Practise next
Python AssertionError exercises → Back to the lesson
Python Booleans examplesPython Exceptions: try, except, else and finally examplesPython ValueError examplesPython Testing examples