Skip to the content

Project: test a function

Python · Unit 20: Testing and debugging

You are going to write a discount function and the tests that protect it.

The rule: discount(p, pct) returns what you pay, and if pct is not between 0 and 100 the price stays as it was.

def discount(p, pct):
    return p - p * pct / 100

print(discount(200, 10))

Prints

180.0

Exercises in this lesson

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

  1. 1. Complete the code

    Complete the test for the impossible percentage.

  2. 2. Write the code

    Write discount(p, pct): return what you pay after applying the percentage. If pct is below 0 or above 100, return the price unchanged.

  3. 3. Write the code

    Here are two versions of discount and one has a bug. Complete check(f) so it prints ok when the function respects the rule about the impossible percentage, and fails when it does not. The calls to check are already written.

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 →