Skip to the content

Writing tests

Python · Unit 20: Testing and debugging

Checking things by hand gets forgotten. If you gather the asserts inside a function whose name starts with test_, you can run them again whenever you want.

It reads like a list of promises: this should give that.

def half(n):
    return n / 2

def test_half():
    assert half(10) == 5
    assert half(0) == 0
    print("half: ok")

test_half()

Prints

half: ok

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Put the lines in order

    Put the lines in order to write the test for add and run it.

  3. 3. Complete the code

    Complete the test for the empty case.

  4. 4. Multiple choice

    You just wrote final_price. What is the best way to test it?

  5. 5. Complete the code

    Complete the test that checks that 7 is not even.

  6. 6. Find the bug

    double is written wrong and the check should catch it, but it says everything is fine. Which line has the error?

  7. 7. Predict the output

    What does this code print?

  8. 8. Find the bug

    This program defines a test and should run it, but the test is nowhere to be seen in the output. Which line has the error?

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →