Ad space (banner)
🐍Python Lessons
Lesson 29 / 69

Checking Correctness with assert (your first step into testing)

This lesson covers using assert for simple sanity checks, so you can build up the basic mindset behind testing. It's written for anyone searching "Python assert tutorial" or "Python how to write tests".

assert condition, message raises an error only when the condition is False. It's the basic idea behind test code — automatically checking whether a function's result matches what you expected. Real-world projects tend to use a dedicated testing tool like pytest, but the underlying idea is the same as this assert.

The sample code uses assert to confirm that add(2, 3) should equal 5, and deliberately checks an incorrect expectation — that it should equal 6 — catching the resulting AssertionError with try...except and displaying its message. Notice the difference: when the condition holds, nothing happens; when it doesn't, an error is raised.

A common beginner mistake is not knowing that Python has an optimization mode which disables assert entirely, which matters if you rely on assert in production code. Since assert can be skipped in this mode, checks you absolutely need to run in production are sometimes safer written as a plain if statement plus an exception instead.

Building the habit of comparing an expected result against an actual one is a key skill for catching bugs early. Getting into the habit of a quick assert sanity-check every time you write a function makes later fixes and refactoring much less nerve-wracking.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)