Python · Stage 10 – Beyond the Basics · Lesson 48 of 50

Testing Your Code

Write one automated check that proves a function returns the expected result.

def add(a, b):
    return a + b
Line-by-line explanation
  1. The function receives two numbers.
  2. Return sends their sum back.
def test_add():
    assert add(2, 3) == 5
Line-by-line explanation
  1. The test function has a descriptive name.
  2. add(2, 3) produces a result.
  3. == 5 describes the expected value.
  4. assert reports failure when the comparison is False.

Tiny Practice

Assert that double(4) returns 8.

Starter template

def double(number):
    return number * 2

assert CHANGE_ME
Line-by-line explanation
  1. The function is ready.
  2. The assertion needs a comparison.
Hint
  1. Call double with 4.
  2. Use ==.
  3. Compare with 8.
Show Solution
def double(number):
    return number * 2

assert double(4) == 8
Line-by-line explanation
  1. Double returns 8.
  2. The comparison is True.
  3. The assertion passes silently.