Use assert for checks

EasyException Handling Programs · 15 of 20

Write a Python program that uses assert to check a condition and handles the AssertionError.

Advertisement
Output
450.0
Error: percent must be 0-100

Approach

  1. assert condition, message raises AssertionError when the condition is false.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment