Python Practice › Exception Handling Programs › Program 15
Use assert for checks
Write a Python program that uses assert to check a condition and handles the AssertionError.
Output
450.0 Error: percent must be 0-100
Approach
assert condition, messageraises AssertionError when the condition is false.
Solution
def apply_discount(price, percent): assert 0 <= percent <= 100, "percent must be 0-100" return price * (1 - percent / 100) print(apply_discount(500, 10))try: apply_discount(500, 150)except AssertionError as e: print("Error:", e)Output
450.0 Error: percent must be 0-100
Watch out
Python skips assert statements when run with -O, so use them for internal checks and tests, not for validating user input.
Learn the concept
New to this topic? Read the lesson, then come back.