You can write code that runs without errors and still be completely wrong. The
If the condition after
assert statement is a lightweight way to check assumptions during development.If the condition after
assert evaluates to True, execution continues silently. If it evaluates to False, Python immediately raises an AssertionError. This makes assertions perfect for catching logic mistakes before they become bugs.Basic syntax
# Passes: 5 is greater than 3
assert 5 > 3, "Five should be bigger"
print("Still running")
# Fails: stops with an AssertionError
# assert 2 + 2 == 5, "Sums are broken"The part after the comma is an optional message. It only appears if the check fails.
Python can be told to skip every
Python can be told to skip every
assert, and some finished programs run that way. So don't use assert to check what a user types in: use if and raise for that, as in the errors lesson. Use assert to check that your own code works the way you expect.Writing test functions
def add(a: int, b: int) -> int:
return a + b
def test_add() -> None:
assert add(1, 2) == 3, "Simple sum failed"
assert add(-5, -5) == -10, "Negatives failed"
test_add()Notice how
This pattern scales well: one test function per feature, each checking several cases.
test_add calls the target function multiple times with different inputs. Each call has its own assertion and message. Run it, and nothing appears: when every check passes, assert stays quiet.This pattern scales well: one test function per feature, each checking several cases.
Edge cases matter most
def first_char(s: str) -> str:
if not s:
return ""
return s[0]
def test_first_char() -> None:
assert first_char("hello") == "h", "Normal"
assert first_char("") == "", "Empty"
assert first_char("x") == "x", "One letter"
test_first_char()Edge cases are inputs at the boundary of what is valid: empty text, zero, negative numbers, lists with one item. They fail more often than everyday values, because they take the less-used paths through your code, like the
Writing tests before or while you write a function forces you to think about these boundaries explicitly. It changes how you design functions — you start asking "what should happen when the list is empty?" before writing
if not s: line above.Writing tests before or while you write a function forces you to think about these boundaries explicitly. It changes how you design functions — you start asking "what should happen when the list is empty?" before writing
for loops.