1. Concept library
  2. Python Foundations
  3. Module 11: Testing

Concept

Assertions

assert states something that must be true at that point in the code, and stops with an AssertionError if it is not. In tests it is how you check a result; in production code it documents assumptions.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what assert does and when Python skips it
  2. Write assertions in a test that check a function's result
  3. Spot an assert used to validate user input and replace it with a raise

In practice

A few lines that show Assertions doing its job.

Python
def median(values):
    s = sorted(values)
    mid = len(s) // 2
    return s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2

assert median([3, 1, 2]) == 2
assert median([4, 1, 3, 2]) == 2.5
assert median([7]) == 7

The common mistake

Watch for

Using assert to validate user input or guard production code. Python skips every assert when run with -O, so the check silently disappears. Raise a real exception instead.

What to know first

Your roadmap puts these before Assertions, unless you already know them.

How it stays learned

Once a session shows you understand Assertions, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Assertions.