…
…
Python Programming Fundamentals · Lesson 39 / 40 · Capstone
PreviewIn this lesson you will
assert test plan with normal, boundary, and invalid input for each function before writing the code, finish the functions one by one by making them pass their tests, and join them in a main flowYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada wants a loyalty card system for Corner Café, and she wrote what she wants in plain prose, a few sentences, and sent it to you. This time nobody tells you which variable to write or which function to build: all you have is Ada's text. In this lesson you will turn that text into a program that works step by step and passes its tests.
So far every lesson told you what to write: "write a function called discount, have it take the amount, and have it return this." In real life, requests do not arrive like that. A friend, a client, or a teacher writes you a few sentences and expects you to do the rest. Ada's message is this:
By the end of the lesson you will have written a program that gives this output from that message:
OutputCC-0042: free coffee!
Rejected: Card not found: CC-04X1
CC-0311: free coffee!
CC-0042 0 points (10 to go)
CC-0107 4 points (6 to go)
CC-0311 0 points (10 to go)There is no new Python command in this program. Everything you will use you have already seen: functions and return (14–16), testing with assert (19), string methods and aligned f-strings (21–22), dictionaries (26–27), raise ValueError and try/except (32). What is new is combining them with a method. Most beginners face an empty file and try to write everything from the first line to the last in one go, then run it and meet a pile of errors. Finding which error comes from where takes hours. The method you will learn in this lesson has four steps, and those four steps work no matter how big the program is.
In this lesson you will:
Before you start writing code, you read the request with four questions. Inputs: what does the program take in, what information does it work with? Outputs: what does the program give back, what appears on the screen or which value is returned? Rules: what happens when, which result comes out under which condition? Examples: with a concrete input, what exactly should happen? The reason for sorting into these four is that prose gives them mixed together. One of Ada's sentences can state an input and a rule at once, and a rule can be left out entirely. When you write it in a table, you can see what is missing.
Let's read Ada's message with these four questions.
Example 1 (case, no code): The request table
| Question | From Ada's request |
|---|---|
| Inputs | Card code (e.g. CC-0042) · number of coffees · registered cards and their points (dictionary) |
| Outputs | The card's current points · whether there is a free coffee or not · a summary line for each card at the end of the day |
| Rules | The code starts with CC- and ends with 4 digits · 1 coffee = 1 point · if points are 10 or more, one coffee is free and 10 points come off · if the code is wrong or the card is not registered, the transaction is rejected |
| Examples | CC-0042 has 8 points and buys 2 coffees → points become 10 → free coffee, points become 0 · CC-04X1 → "Card not found" |
While filling in the table, something should have caught your attention: the sentence "When the points reach 10" can be read in two ways. When a customer with 9 points buys a coffee, is that coffee the 10th and free, or is it the 11th coffee, after the points have reached 10? Ada did not write it. Do not close an ambiguity like this with a guess; make it concrete with an example and ask: "A customer with 9 points bought a coffee. The points became 10. Did they earn a free coffee with this one?" Ada says "yes, the free coffee is earned at that moment and the points drop to 0." You write this answer in the table as an example too: 9 points + 1 coffee = 10 → free, points 0. In a moment this example will turn into a test; that way the rule is never ambiguous again.
Now put the sentences of the request into the right roles. A sentence sometimes states an input and sometimes a rule; sentences with concrete numbers are usually examples.
Match each piece of Ada's request with its role.
For each row, pick its match from the list, then check.
CC-0042"The table is ready. Now you turn each rule or output into a function that does one job. Remember the rule from lesson 16: if you cannot name a function with the name of a single job, that function should be split. There are four jobs in Ada's request:
| Function | Takes | Returns | Which rule or output |
|---|---|---|---|
is_valid_code(code) | card code | True or False | The code is CC- + 4 digits |
add_points(cards, code, count) | dictionary, code, count | the new points; ValueError for an invalid or unregistered code | 1 coffee = 1 point, a wrong code is rejected |
redeem_reward(cards, code) | dictionary, code | True (free coffee) or False | 10 points and above: free, points − 10 |
summary_line(code, points) | code, points | one aligned line of text | The end-of-day table |
These functions depend on each other. add_points has to know whether a code is valid before accepting it, so it will call is_valid_code. That is why the writing order is the dependency order: first is_valid_code, which depends on nothing, then add_points, which depends on it, then redeem_reward and summary_line. If you start with the function that depends on nobody, what you test at each step is built on parts that really work.
Before writing the bodies of the functions, you write their skeletons: the def line of each and a one-line docstring that says what it does. In lesson 14 you saw that the docstring is the first line of a function and describes what it takes and what it returns. A skeleton is the perfect place for this docstring: you turn the "takes" and "returns" columns of the function table into a sentence. A function whose body is only a docstring is valid for Python. When called, it computes nothing, and because there is no return, it returns None. This is very useful: the program runs without errors from the first minute, and you fill in the bodies one by one later.
Before reading the code, predict: what comes out on the screen when this skeleton runs?
What appears on the screen when this code runs?
def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" print(is_valid_code("CC-0042"))
Example 2 (case): The skeleton of the four functions
def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" def add_points(cards, code, count): """Add count points to a registered card and return the new points. Raise ValueError if the code is invalid or not registered. """ def redeem_reward(cards, code): """If points are 10 or more, take off 10 points and return True, otherwise return False.""" def summary_line(code, points): """Return the card code, its points, and the coffees left until the reward as one aligned line.""" print(is_valid_code("CC-0042"))
OutputNoneWe have not written a single calculation yet, but the program already carries a plan. Each function's name, inputs, and promise (the docstring) are set. The pass you saw in lesson 16 does the same job; the difference of a skeleton with a docstring is that it already tells you what you will write.
"But why four functions? Wouldn't one big function mean less code?" Let's answer this with a scenario.
There are two plans. A: a single card_action(cards, code, count) function checks the code, adds the points, gives the reward, and prints the result. B: the four functions above. If Ada says tomorrow "Let's make Fridays double points", in which plan does the change stay in one place and can also be tested on its own?
When a function does several jobs, the code can get a bit shorter, but every change puts all the jobs at risk and you cannot try any part separately. Separate the jobs that calculate from the jobs that print in particular: a function that calculates gives its result with return, so a test can catch it. You cannot check text printed to the screen with assert.
It is time to write the first function. But there is one more step first: the test plan. Before writing the code, you answer the question "if this function works correctly, what should it return for which input?" and turn the answers into assert lines. In lesson 19 you saw three kinds of input: normal input (a typical case), boundary input (the two sides right at the threshold where the rule changes), and invalid input (a value the function should not accept).
Why do you write the test first? If you write the test after the code, without noticing you test what your code already does. When you write it first, the tests look at the request, not at the code. There is something else too: writing the test plan makes you think about the request once more. The question "what happens if someone writes cc-0042 in lowercase?" only comes to mind while writing tests.
The whole process works like this: write the tests, run them and watch them fail (there is no body yet, so they have to fail); write the function; run the tests again; when they all pass, move to the next function. At the very end, join the functions in the main flow. Build this order yourself.
Put the steps of turning a request into a program in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The test plan table for is_valid_code:
| Input | Kind | Expected | Why |
|---|---|---|---|
"CC-0042" | normal | True | Matches the rule exactly |
"CC-004" | invalid | False | One digit missing |
"CC-00A2" | invalid | False | A letter instead of a digit |
"cc-0042" | invalid | False | The prefix is lowercase |
"CC-00042" | invalid | False | One digit too many |
You turn this table into code with each row as one assert. The skeleton still has no body; let's see what happens when we run the tests.
Example 3 (case): The tests fail first
def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" # Test plan: is_valid_code assert is_valid_code("CC-0042") == True, "normal: valid code" assert is_valid_code("CC-004") == False, "missing digit" assert is_valid_code("CC-00A2") == False, "letter instead of digit" assert is_valid_code("cc-0042") == False, "lowercase" assert is_valid_code("CC-00042") == False, "extra digit" print("is_valid_code: all tests passed")
On the screen:
OutputTraceback (most recent call last):
File "<code>", line 5, in <module>
assert is_valid_code("CC-0042") == True, "normal: valid code"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: normal: valid codeThe first test failed, because the skeleton returns None and None == True is false. This is not a failure, it is what we expected: it shows that the test really checks something. A test that never fails catches nothing. Now we write the body: the code must be exactly 7 characters, it must start with CC-, and what comes after the third character must be digits. The slice, startswith, and isdigit from lessons 20–21 are made for exactly this job.
def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" return len(code) == 7 and code.startswith("CC-") and code[3:].isdigit() # Test plan: is_valid_code assert is_valid_code("CC-0042") == True, "normal: valid code" assert is_valid_code("CC-004") == False, "missing digit" assert is_valid_code("CC-00A2") == False, "letter instead of digit" assert is_valid_code("cc-0042") == False, "lowercase" assert is_valid_code("CC-00042") == False, "extra digit" print("is_valid_code: all tests passed")
Outputis_valid_code: all tests passedAll five tests passed. is_valid_code is now a reliable part; we can build add_points on top of it. Before that, make sure you can tell the kinds of test input apart. We thought of tests for add_points and redeem_reward too; choose the kind of each one.
Match each test input with its kind.
For each row, pick its match from the list, then check.
is_valid_code("CC-0042")is_valid_code("CC-004")add_points(cards, "CC-9999", 1) (a card that is not registered)To see what is inside a test, let's open up is_valid_code a little: we wrote the three conditions into separate variables. Follow the code step by step. At each assert line, watch the function being entered, how the length_ok, prefix_ok, and digits_ok boxes fill up, and which result the return produces from them. Then, with "Change the code", turn the line digits_ok = code[3:].isdigit() into digits_ok = True and trace it again: where does the third test ("CC-00A2") fail, and why?
Run the code line by line: see which line runs next, the variable boxes and the output.
def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" length_ok = len(code) == 7 prefix_ok = code.startswith("CC-") digits_ok = code[3:].isdigit() return length_ok and prefix_ok and digits_ok assert is_valid_code("CC-0042") == True, "normal: valid code" assert is_valid_code("CC-004") == False, "missing digit" assert is_valid_code("CC-00A2") == False, "letter instead of digit" print("Three tests passed")
For "CC-004", length_ok became False on the very first line and the result came out False. "CC-00A2" is 7 characters and starts with CC-; the only condition that rejects it is isdigit. When you broke that line, the only test that caught the letter code was that one. This is what it means for each test to protect a certain rule: when a rule breaks, the test that protects it fails and tells you which rule is broken.
To see why boundary values need to be tried separately, look at the rule of redeem_reward. The code below works out whether there is a free coffee and how many coffees are left until the next reward. Change the value of points in turn: 8, 9, 10, 19, 20.
Change the points: at which value does the free coffee start?
Pick a value; predict the output first, then look.
1points = 92free = points >= 103remaining = 10 - points % 104print(free, remaining)
False 1
Faded lines didn't run with this value. Between 9 and 10, free flips from False to True: the rule changes exactly at this threshold. remaining is 1 at 9 and goes back to 10 at 10, is 1 at 19 and goes back to 10 at 20. If a test tried only 8 or 15, it would not notice that > was mistakenly written instead of >= 10; only the exact value 10 catches the mistake. That is why both sides of the boundary (9 and 10, 19 and 20) are tested separately.
We continue with the same loop: test plan, failing tests, body, passing tests. Three tests are a good start for add_points: adding 2 coffees to a card with 3 points should return 5 (normal), the new points should also be written into the dictionary, and a card that is not registered should be rejected with ValueError (invalid). For the last test we use the try/except pattern from lesson 32: we call the function with an unregistered card; if it raises ValueError, the rejected variable becomes True, and then we check with assert rejected that this really happened.
In the cell below is_valid_code is ready and add_points is only a skeleton. This time the tests are inside a try block: if a test fails, the program does not stop, it prints which test failed. Your task has three steps: (1) Run it and read which test failed. (2) Write the body of add_points: if the code is invalid or not in the dictionary, raise ValueError(f"Card not found: {code}"); otherwise increase the points, write them into the dictionary, and return the new points; run it until the three tests pass. (3) Ada sent a new request: "Reject it if the number of coffees is 0 or negative." First write its test (add_points(cards, "CC-0042", 0) should be rejected), run it and see it fail, then fix the function.
Try it now· not graded; doesn't affect progress
redeem_reward and summary_line are written the same way; you will find the boundary tests of redeem_reward in the Examples section below. When all four functions pass their tests, the last step comes: the main flow. The day's sales arrive as text like "CC-0042:2" (card code, colon, number of coffees). We split each text in two with split(":"), convert the count to a number with int, and call add_points first and redeem_reward second. An unregistered or faulty card raises ValueError; we catch it with try/except, so one faulty transaction does not stop the whole day's flow. We also turn the reward threshold, 10, into an uppercase constant: if Ada lowers the threshold to 8 one day, only one line changes.
Example 4 (case): The target program
REWARD_THRESHOLD = 10 def is_valid_code(code): """Return True if the card code starts with CC- and ends with 4 digits.""" return len(code) == 7 and code.startswith("CC-") and code[3:].isdigit() def add_points(cards, code, count): """Add count points to a registered card and return the new points.""" if not is_valid_code(code) or code not in cards: raise ValueError(f"Card not found: {code}") cards[code] = cards[code] + count return cards[code] def redeem_reward(cards, code): """If the points reached the threshold, take off that many points and return True.""" if cards[code] >= REWARD_THRESHOLD: cards[code] = cards[code] - REWARD_THRESHOLD return True return False def summary_line(code, points): """Return the card code, its points, and the coffees left until the reward as one aligned line.""" remaining = REWARD_THRESHOLD - points % REWARD_THRESHOLD return f"{code:<9}{points:>3} points ({remaining} to go)" cards = {: 8, : 3, : 9} transactions = [, , , ] transaction transactions: code, count = transaction.split() : add_points(cards, code, (count)) redeem_reward(cards, code): (f) ValueError error: (, error) code, points cards.items(): (summary_line(code, points))
OutputCC-0042: free coffee!
Rejected: Card not found: CC-04X1
CC-0311: free coffee!
CC-0042 0 points (10 to go)
CC-0107 4 points (6 to go)
CC-0311 0 points (10 to go)Compare the program with Ada's request. CC-0042 had 8 points, reached 10 with 2 coffees, and won a free coffee; the example in the table held. CC-0311 had 9 points and got the reward on the 10th coffee; the example we settled with Ada held too. CC-04X1 is an invalid code; the program rejected it but did not stop, and moved on to the next transaction. The end-of-day table came out in neat columns with the alignment formats of lesson 22: :<9 left-aligns the code in a 9-character field, and :>3 right-aligns the points in a 3-character field.
Notice one thing: the tests of all four functions had passed, and we still ran the main flow separately with sample data. You will see why that is needed in a moment, in the pitfalls section.
The method is not specific to the café. A request from a library: "A book is free for 14 days; after that every day is $0.25; the fee is at most $2.00." Let's analyze it with the four questions. Input: the number of days the book was kept. Output: the late fee ($). Rules: up to 14 days the fee is 0; after that $0.25 per day; the fee does not go above $2.00. Example: 20 days → 6 days late → $1.50. There is a single job, so a single function is enough.
In the test plan, watch the boundaries: day 14 is still free (the last free day), day 15 is the first paid day. There is also a cap: to see that the fee stops at $2.00, a value above the cap (40 days) must be tried. That way the four tests protect every rule at least once.
Example 5 (outside the case): Library late fee
def late_fee(days): """Return the late fee ($) from the number of days the book was kept.""" late_days = days - 14 if late_days <= 0: return 0 return min(late_days * 0.25, 2.00) assert late_fee(10) == 0, "normal: not due yet" assert late_fee(14) == 0, "boundary: last free day" assert late_fee(15) == 0.25, "boundary: first paid day" assert late_fee(40) == 2.00, "cap: at most $2.00" print("late_fee: all tests passed") print(late_fee(20), late_fee(29), late_fee(30))
Outputlate_fee: all tests passed
1.5 2.0 2.0For the cap, the min you saw in lesson 5 was used: it returns the smaller of the calculated fee and $2.00. At 29 days the lateness is 15 days and the fee would be $3.75, but min holds it at $2.00; at 30 days the calculation gave $4.00, and min held it at $2.00 too. Put the lines of the function and its two tests in the right order to build the method once more.
Put the late_fee function and its two tests in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
First pitfall: leaving the body completely empty. If you forget the docstring too while setting up the skeleton, the function has no body at all:
def is_valid_code(code): print(1)
On the screen:
Output File "<code>", line 3
print(1)
^^^^^
IndentationError: expected an indented block after function definition on line 1Put simply: "an indented block was expected after the function definition on line 1." Python wants at least one indented line under the def line. A docstring is exactly such a line; if you set up the skeleton with a docstring, you never see this error. A skeleton is not broken; only a function with no body at all is.
Second pitfall: the tests pass, the program is wrong. Say the order of the two calls in the main flow changed: redeem_reward is called before add_points. The functions are as in Example 4; only the loop changed, and the points are printed after each transaction:
cards = {"CC-0311": 9}
transactions = ["CC-0311:1", "CC-0311:1"]
for transaction in transactions:
code, count = transaction.split(":")
try:
if redeem_reward(cards, code):
print(f"{code}: free coffee!")
add_points(cards, code, int(count))
except ValueError as error:
print("Rejected:", error)
print(code, "points:", cards[code])On the screen:
OutputCC-0311 points: 10
CC-0311: free coffee!
CC-0311 points: 1When the customer with 9 points bought the 10th coffee, the reward attempt was made while the points were still 9, and no free coffee came out; the reward came only at the 11th coffee. The rule we settled with Ada was "free on the 10th coffee". All the tests of the four functions still pass, because each function does its own job correctly; what is wrong is the order they are called in. Unit tests check the parts; they do not check how the parts are joined. That is why in the last step you also run the main flow with the examples from the request: the example "1 coffee on a card with 9 points: free coffee, points 0" catches this error on the first try.
redeem_reward (case)The reward rule has two thresholds: between 9 and 10 (the reward is born) and a case like 19 points that passes the threshold once (only one reward, the remaining points are kept). Next to each test it says which rule it protects.
REWARD_THRESHOLD = 10 def redeem_reward(cards, code): """If the points reached the threshold, take off that many points and return True.""" if cards[code] >= REWARD_THRESHOLD: cards[code] = cards[code] - REWARD_THRESHOLD return True return False # Test plan: redeem_reward (both sides of the boundaries) cards = {"CC-0042": 9, "CC-0107": 10, "CC-0311": 19} assert redeem_reward(cards, "CC-0042") == False, "boundary: 9 points is not enough" assert cards["CC-0042"] == 9, "no reward, points do not change" assert redeem_reward(cards, "CC-0107") == True, "boundary: 10 points is enough" assert cards["CC-0107"] == 0, "10 points come off with a reward" assert redeem_reward(cards, "CC-0311") == True, "19 points: one reward" cards[] == 9, ()
Writing the test after the code is finished, and with a single normal input. In the late_fee below the cap has been forgotten. The single normal test passes and the program is thought to be correct:
def late_fee(days): """Return the late fee ($) from the number of days the book was kept.""" late_days = days - 14 if late_days <= 0: return 0 return late_days * 0.25 assert late_fee(20) == 1.5, "normal: 6 days late" print("Test passed")
OutputTest passedIf a test had been written for every rule in the request, the cap rule would have gotten a test too. When the line assert late_fee(40) == 2.00, "cap: at most $2.00" is added, the error shows up right away:
OutputAssertionError: cap: at most $2.00The right way: write the test plan before the code, looking at the request's table. Have at least one test for every rule, one from each side of every threshold, and one for every kind of invalid input. A single normal test only says "correct for this input".
None, the program runs), and write the functions in the order they depend on each other.Next lesson: In the capstone project you will apply this method to a bigger request: Mini bank or Adventure game.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Outputredeem_reward: all tests passedThe tests look not only at the returned value but also at the points in the dictionary. redeem_reward may look like it does two jobs (the decision and taking off points), but both are parts of the same rule: "redeeming a reward". The function's promise is written in the docstring, and the tests check every part of this promise.
The request: "If the basket is $25 or more, shipping is free; below that it is $2. If the package is over 10 kg, $0.25 is added for every kilo over." The analysis is in the comment lines, and the tests cover the boundaries of the two rules and the case where the two rules work together.
# Inputs: basket total ($), weight (kg) · Output: shipping fee ($) # Rules: if total >= 25 the fee is 0, otherwise 2; # if weight > 10, (weight - 10) * 0.25 is added def shipping_fee(total, weight): """Return the shipping fee ($) from the basket total and the package weight.""" fee = 0 if total < 25: fee = 2 if weight > 10: fee = fee + (weight - 10) * 0.25 return fee assert shipping_fee(15, 2) == 2, "normal: cheap and light" assert shipping_fee(24.75, 2) == 2, "boundary: just under $25" assert shipping_fee(25, 2) == 0, "boundary: exactly $25" assert shipping_fee(25, 10) == 0, "boundary: exactly 10 kg has no extra charge" assert shipping_fee(25, 12) == 0.5, "heavy package: 2 kg over" assert shipping_fee(10, 13) == 2.75, "cheap and heavy: both rules together" print("shipping_fee: all tests passed")
Outputshipping_fee: all tests passedBecause the two rules are independent of each other, there are two separate if statements, not elif: a cheap and heavy package pays both fees. The last test checks exactly this: $2 + 3 × $0.25 = $2.75.