Use a small Python assertion to check a known answer

← Back to Blog & Articles

An assertion checks that a condition is true during program execution. It is useful for a small learning exercise when you already know the expected result.

Worked example

After writing a function that adds a bonus of two to a score, check that applying it to three returns five. If the assertion fails, Python raises AssertionError. You can inspect the function and the expected result to understand which assumption was wrong. Add a case with a zero score to check another boundary.

What to check

Choose expectations independently of the implementation. Copying the same mistaken calculation into both the function and the assertion can hide the error. Assertions can be disabled in optimized Python execution, so use ordinary validation and explicit error handling for rules that must always protect a running application. For learning, a few known-answer checks give quick feedback and make the function’s intended behavior concrete.

Continue with the book

Explore the full treatment, worked examples, and exercises in Code Quest with Python.


Companion article for Code Quest with Python, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top