AssertionError · Exercises
Core Python

AssertionError Exercises

4 exercises that build on the Python AssertionError lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: An AssertionError means an assert statement checked a condition that turned out to be False, so something your code assumed to be true was not. By the end you can write assert statements with useful messages, diagnose why one fails, avoid the tuple and float pitfalls, and know when to raise a real exception instead. You will practise: Predict which asserts fail; Make the guard work; Validate with ValueError; Validate input, assert the result.

0 / 4 completed

AssertionError practice exercises

1. Predict which asserts fail

Predict the output Easy

Read the code and type exactly what it prints, then press Check.

Read this code
checks = [(5, "small"), (50, "large"), (500, "huge")]

for value, label in checks:
    try:
        assert value < 100, f"{label} value {value}"
        print("ok", value)
    except AssertionError as err:
        print("failed:", err)

2. Make the guard work

Fix the bug Easy

withdraw(balance, amount) should raise an AssertionError with the message "Insufficient funds" when amount is bigger than balance. At the moment the assert never fails. Fix the function.

Your code
def withdraw(balance, amount):
    assert (amount <= balance, "Insufficient funds")
    return balance - amount

print(withdraw(100, 30))

3. Validate with ValueError

Write code Medium

The function check_discount(percent) receives a value typed by a shopper. It should return percent when it is between 0 and 100 (inclusive) and otherwise raise a ValueError (not an AssertionError, because assertions can be switched off).

Your code
def check_discount(percent):
    assert 0 <= percent <= 100
    return percent

4. Validate input, assert the result

Write code Hard

Write normalize(weights) that returns a list where each weight is divided by the sum, so the results add up to 1. Raise ValueError if the list is empty or the sum is not positive (that is bad input). After computing the result, use an assert with math.isclose to check your own invariant that the new list sums to 1.

Your code
import math

def normalize(weights):
    pass

Next lessonPython StopIteration

More Python AssertionError examples · All Python exercises