…
…
Python Programming Fundamentals · Lesson 40 / 40 · Capstone
PreviewIn this lesson you will
reset(), check first then change, and tests that expect an error together in one small programassertYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Corner Café is starting to sell gift cards: a customer loads money onto a card, the register spends from the card, and the cashier types the transactions as short commands. Ada has only one condition: a transaction that breaks a rule must leave no trace on the card. In this lesson you will build this small program with its tests, then use the same patterns to choose your final project and finish it.
You have reached the last stop of the course. There is no new Python concept in this lesson; you will combine the pieces you have learned so far into three patterns that appear in every real program. The gift card program you write at the end of the lesson will first run its own tests, then process the cashier's four commands:
OutputAll tests passed
> load GC-02 2.50 => 2.5
> SPEND gc-02 1.00 => 1.5
> spend GC-02 4.50 => Error: Insufficient balance: $1.50 available
> dance now => Error: Unknown command: dance nowNotice three things: a command typed in capital letters is understood, a spend that breaks the rules does not stop the program, and a nonsense command is politely rejected. Each of these three behaviors comes from a pattern that you will build one by one below.
After this lesson you will choose one of two final projects. Both are guided projects that go step by step, and every step is checked automatically.
Mini bank. You write a small bank with three accounts: deposit, withdraw, and transfer between two accounts. A negative amount, a missing account, an insufficient balance, and a transfer to the same account are rejected. Successful transactions are written to a log, and at the end of the day the log is saved to a CSV file. A part of the end-of-day batch of transactions:
OutputRejected (withdraw): Insufficient balance: $0.00 available
Rejected (withdraw): Amount must be greater than zero
Rejected (transfer): Cannot transfer to the same account
3/6 transactions succeededAdventure game. You write a text game with four rooms. The player types commands such as go north and take lantern, and collects items in an inventory. The door to the cellar is locked and needs a key, and the cellar is pitch dark without the lantern. A part of the end of the game:
Output> go down
The door is locked. You need the key.
...
> take treasure
You took the treasure.
Congratulations! You found the treasure in 6 moves.To decide which one to choose, look at which lessons each one relies on most:
| Mini bank | Adventure game | |
|---|---|---|
| State | Account dictionary and log list | Rooms (nested dictionary) and player dictionary |
| Lessons used most | Dictionary (26), raising errors (32), CSV (34) | Nested dictionary (28), list (23), string methods (21), copy (25) |
| Example rule | A withdrawal with an insufficient balance is rejected | You cannot pass a locked door without the key |
| Good for | People who like working with numbers and records | People who like working with text and stories |
Whichever you choose, there is a minimum requirement for the project to count as finished: your program will have at least 3 functions, and you will write at least 1 `assert` test for each of them. "The code runs" does not meet this requirement; there must also be tests that show the code works correctly.
In this lesson you will:
reset(), check first then change, a test that expects an error) in the gift card program.reset()The "state" of a program is all the information that changes while it runs: the balances of the cards, the accounts in a bank, the room the player is in. If this information is scattered all over the program, it becomes hard to follow which piece changed and when. So the first pattern is this: all the changing state lives in one dictionary. In the gift cards program this dictionary is called cards; the key is the card code and the value is the balance.
The second piece is the reset() function, which returns this dictionary to its starting state. Why is it needed? In projects, every cell and every test makes its own attempt: one spends $1.50 from a card, another tries to spend from an empty card. If the state starts from a different point each time, the same test passes in one run and fails in the next. reset() starts every attempt from the same beginning.
reset() uses two dictionary methods. cards.clear() empties the dictionary, and cards.update({...}) adds the given pairs to it. Neither builds a new dictionary; both change the contents of the existing one. In lesson 16 you saw that assigning to a name inside a function makes that name local; here there is no assignment to the name cards at all, and as in lesson 25 the contents of the same dictionary are changed in place. That is why you do not need anything like global.
The function that uses the card is spend(code, amount). It has two steps, marked with comments: first check the rules, then change the balance.
Example 1 (case): Gift cards and spending
cards = {}
def reset():
cards.clear()
cards.update({"GC-01": 5.00, "GC-02": 0.00})
def spend(code, amount):
# 1. Check first
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if code not in cards:
raise ValueError(f"Card not found: {code}")
if amount > cards[code]:
raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")
# 2. Then change
cards[code] -= amount
return cards[code]
reset()
print(spend("GC-01", 1.50))
try:
spend("GC-01", 25.00)
except ValueError as error:
print(error)
print(cards["GC-01"])Output3.5
Insufficient balance: $3.50 available
3.5The first spend passes all the rules: the amount is positive, the card is registered, and the balance is enough. The balance goes from $5.00 down to $3.50. The second spend is stopped at the third check: $25.00 is more than the $3.50 balance. When the raise line runs, the function ends there; the subtract line below it is never reached. The error is caught by the try on the calling side and printed, and the last line shows that the balance is still 3.5. The rejected transaction left no trace.
Follow the code below step by step. In the rejected call, look at the cards box: does it change? Which line runs after the raise line? Then change the 25.00 in the last call to 3.5 and trace it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
cards = {}
def reset():
cards.clear()
cards.update({"GC-01": 5.00, "GC-02": 0.00})
def spend(code, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if code not in cards:
raise ValueError(f"Card not found: {code}")
if amount > cards[code]:
raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")
cards[code] -= amount
return cards[code]
reset()
print(spend("GC-01", 1.50))
try:
spend("GC-01", 25.00)
except ValueError as error:
print(error)
print(cards)After the raise line, the flow jumps straight to the except block; the cards[code] -= amount line is never highlighted in the rejected call. This is exactly what the second pattern asks for.
A function that changes state first checks all the rules and raises a ValueError if one is broken; the state changes only after all the checks pass. Why does this order matter so much? Because raising an error does not undo the changes made up to that point. A function that makes the change first and checks later gives the right error, but it has already damaged the balance.
Below is a version that sets this order the wrong way around: it subtracts first, then checks whether the balance went below zero. Predict the result before running it.
A $7.50 spend is tried on a card that has $5.00. What does the last line print?
card = {"GC-01": 5.00}
def spend_broken(code, amount):
card[code] -= amount
if card[code] < 0:
raise ValueError("Insufficient balance")
return card[code]
try:
spend_broken("GC-01", 7.50)
except ValueError as error:
print(error)
print(card["GC-01"])A real run confirms your prediction:
card = {"GC-01": 5.00}
def spend_broken(code, amount):
card[code] -= amount
if card[code] < 0:
raise ValueError("Insufficient balance")
return card[code]
try:
spend_broken("GC-01", 7.50)
except ValueError as error:
print(error)
print(card["GC-01"])OutputInsufficient balance
-2.5The message is right, the result is wrong. The customer sees "your transaction was rejected", but $7.50 has been taken from the card. This kind of error is the most dangerous, because the program does not crash and everything looks fine. The transfer rule in the mini bank rests on the same principle: while money moves from one account to another, no balance changes until both accounts have been found. If you take the money from the source while the target account does not exist, the money is lost in the middle.
Now see how the correct version reacts to different amounts. Put 1.5, 5, 7.5, and -0.25 into the amount box one by one. Which check steps in for which amount, and which lines never run?
Put different amounts into the amount box. Which check steps in, and for which amounts does the subtract line (13) run?
Pick a value; predict the output first, then look.
1amount = 1.52cards = {}3def reset():4 cards.clear()5 cards.update({"GC-01": 5.00, "GC-02": 0.00})6def spend(code, amount):7 if amount <= 0:8 raise ValueError("Amount must be greater than zero")9 if code not in cards:10 raise ValueError(f"Card not found: {code}")11 if amount > cards[code]:12 raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")13 cards[code] -= amount14 return cards[code]15reset()16try:17 print(spend("GC-01", amount))18except ValueError as error:19 print("Error:", error)
3.5
Faded lines didn't run with this value. 1.5 and 5.0 pass all the checks, and the balance goes down. 7.5 is rejected at the third check because it is more than the balance, and -0.25 is rejected at the first check. In both rejected cases, line 13 (cards[code] -= amount) is not among the lines that run: check first, then change.
1.5 and 5.0 pass all the checks; spending $5.00 empties the card completely, which is allowed by the rules. 7.5 stops at the third check, and -0.25 stops at the very first check. Look at the lines that run: in both rejected cases the cards[code] -= amount line is not in the list.
In lesson 19 you used assert to check correct results: "after spending $1.50, $3.50 should be left." But how do you test that a rule rejects a transaction? Spending from an empty card must raise an error; if it does not, the rule is broken. A pattern with three parts is used for this:
1. Try the operation inside try.
2. Right below it, write assert False, "message". If the operation did not raise an error, the flow reaches this line; assert False always fails and stops the test with its message.
3. Under except ValueError:, write pass. If the expected error came, the flow skips assert False, arrives here, and quietly continues.
Add one more piece: also check with assert that the state did not change after the rejection. Otherwise a function like the broken version above, "raises an error but damages the balance", would pass its test.
Example 2 (case): The test function of the gift card
cards = {}
def reset():
cards.clear()
cards.update({"GC-01": 5.00, "GC-02": 0.00})
def spend(code, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if code not in cards:
raise ValueError(f"Card not found: {code}")
if amount > cards[code]:
raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")
cards[code] -= amount
return cards[code]
def run_tests():
reset()
# normal: correct result
assert spend("GC-01", 1.50) == 3.5, "normal spend"
# rule: spending from an empty card must be rejected
try:
spend("GC-02", 0.25)
assert False, "Spending from an empty card was allowed"
except ValueError:
pass
# a rejected transaction must leave no trace
assert cards["GC-02"] == 0, "The rejected spend changed the balance"
reset()
print("All tests passed")
run_tests()OutputAll tests passedA question that comes up often here: assert False raises an AssertionError; will except ValueError not catch and swallow it? It will not. except ValueError catches only errors of the ValueError type, and the AssertionError passes right by it and stops the test. That is exactly why the pattern works. Notice that the test function has reset() both at the start and at the end: the test makes its attempt from a clean state and also leaves a clean state behind.
The lines of a test that expects an error are mixed up below. Put them in the right order, and pay attention to the indentation.
Put in order the lines of the test that checks that spending from an empty card is rejected and the balance does not change.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A test has one more job: to actually catch a bug in the code. For that, what you check matters. In operations that change two things, for example the transfer in the mini bank, you need to check both sides. Step 5 of the mini bank runs its test against a transfer that was broken on purpose and checks this.
A broken transfer takes money out of the source account but forgets to add it to the target. Which test catches this bug?
The rule is simple: whatever an operation changes, the test looks at all of it. A transfer changes two balances; the test checks both balances.
The cashier does not type function calls into the program, but text such as load GC-02 2.50. In the adventure game, the player types go north as well. The shared piece of the two projects is a command parser that turns this text into a function call. Its steps are:
1. Make the text lowercase with lower(), so SPEND and spend are the same (lesson 21).
2. Split it at the spaces with split(): "load GC-02 2.50" → ['load', 'gc-02', '2.50'].
3. Send it to the right function by the first word and the number of words.
4. Convert the part that should be a number with float(); "2.50" is still a string (lesson 4).
5. Reject an unknown command with a ValueError.
One detail: making the text lowercase also turned the card code into gc-02, but the key in the dictionary is GC-02. So when passing the code to the function, we make it uppercase again with upper(). The main flow tries each command inside try; the rejection of one command does not stop the ones after it. Because loading and spending make the same two checks (amount and card), we moved these checks into one single-job function called check_card (lesson 16).
Example 3 (case): Register commands
cards = {}
def reset():
cards.clear()
cards.update({"GC-01": 5.00, "GC-02": 0.00})
def check_card(code, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if code not in cards:
raise ValueError(f"Card not found: {code}")
def load(code, amount):
check_card(code, amount)
cards[code] += amount
return cards[code]
def spend(code, amount):
check_card(code, amount)
if amount > cards[code]:
raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")
cards[code] -= amount
return cards[code]
def command(text):
parts = text.lower().split()
if len(parts) == 3 and parts[0] == "load":
return load(parts[1].upper(), float(parts[2]))
elif len(parts) == 3 and parts[0] == "spend":
return spend(parts[1].upper(), float(parts[2]))
else:
raise ValueError(f"Unknown command: {text}")
reset()
text [, , , ]:
:
(f)
ValueError error:
(f)Output> load GC-02 2.50 => 2.5
> SPEND gc-02 1.00 => 1.5
> spend GC-02 4.50 => Error: Insufficient balance: $1.50 available
> dance now => Error: Unknown command: dance nowThe second command was understood even though it was typed in capital letters, because it was made lowercase first. The third command hit a rule, and the balance stayed at 1.5. The first word of the fourth command was not recognized, so it fell to the else branch. The word-count check (len(parts) == 3) matters too: in a command with a missing amount such as spend GC-01, there is no parts[2], and without this check the program would stop with an IndexError.
Your turn. Example 3 is ready below. Try two things: (1) Add a balance GC-01 command that returns the balance of the card; this command has two words, so write a new elif branch with a len(parts) == 2 check. (2) Then add the command spend GC-01 (amount missing) to the list: which message do you get, and why?
Try it now· not graded; doesn't affect progress
The three patterns are not specific to gift cards. Think of a small parking lot with room for 3 cars: a car enters, a car leaves, and the sign at the entrance shows how many spaces are used. The state is again in a single dictionary (capacity and the list of cars inside), and reset_lot() returns it to the start. Entering and leaving check first, then change the list.
Example 4 (outside the case): Parking lot
lot = {}
def reset_lot():
lot.clear()
lot.update({"capacity": 3, "cars": []})
def enter(plate):
# 1. Check first
if len(lot["cars"]) >= lot["capacity"]:
raise ValueError("Lot is full")
if plate in lot["cars"]:
raise ValueError(f"Car already inside: {plate}")
# 2. Then change
lot["cars"].append(plate)
return len(lot["cars"])
def leave(plate):
if plate not in lot["cars"]:
raise ValueError(f"Car is not inside: {plate}")
lot["cars"].remove(plate)
return len(lot["cars"])
def status():
used = len(lot["cars"])
free = lot["capacity"] - used
return f"Used: {used} Free: {free}"
reset_lot()
enter("ABC-101")
enter("DEF-202")
print(status())
(leave(), status())
enter()
enter()
:
enter()
ValueError error:
(error)
(status())OutputUsed: 2 Free: 1
1 Used: 1 Free: 2
Lot is full
Used: 3 Free: 0The fifth entry was rejected, and the last line shows that the lot is still full with 3 cars: the rejected entry was not added to the list. With its three functions (enter, leave, status), this program already meets half of the minimum requirement. The other half is the tests for each of them; you will write those yourself in the exercises.
Now go back to your project. In lesson 39 you learned to break down a request with four questions: what it takes, what it gives, which rules apply, which examples. Before starting the project steps, fill in the same table for the project you choose. Below are filled-in example tables for both projects.
Example 5 (project plan): Mini bank
| Question | Answer |
|---|---|
| Inputs | Account number, amount; for a transfer, the source and target accounts |
| Rules | A zero or negative amount, a missing account, an insufficient balance, and a transfer to the same account are rejected; a rejected transaction changes neither the balance nor the log |
| Outputs | New balance, transaction log, CSV file of the log, aligned account summary |
| Function list | find_account, check_amount, deposit, withdraw, transfer, run_tests |
Example 5 (project plan): Adventure game
| Question | Answer |
|---|---|
| Inputs | The command text the player types (go north, take lantern, look, inventory) |
| Rules | You cannot go in a direction with no exit; you cannot pass the locked door without the key; in the dark cellar nothing can be seen or taken; an item that is not in the room cannot be taken |
| Outputs | The description of the room, item messages, error messages, move count |
| Function list | look, go, take, command, run_tests |
In both lists, each rule will be checked inside a function, in the first lines, and a test that expects an error will be written for each rule. Below are sentences from the requests of the two projects. Match each one to the lesson or pattern it relies on.
Which lesson or pattern does each sentence in the project requests rely on?
For each row, pick its match from the list, then check.
go northWhen the plan is ready, here is a final checklist: look at these five items before you hand in the project.
| Minimum requirement checklist | |
|---|---|
| At least 3 functions | Not counting reset and run_tests |
At least 1 assert for each function | The name of the function appears in at least one test |
| At least one test that expects an error | try + operation + assert False + except ValueError: pass |
| A rejected transaction does not change the state | After the rejection, the state is checked with assert |
Every cell starts with reset() | No matter how many times you run the cell, you get the same result |
Each item also has a way to check it. Match them.
Match each item of the minimum requirement with how you check it.
For each row, pick its match from the list, then check.
Two mistakes are the most common in a command parser. The first is leaving the part that should be a number as a string: load(parts[1], parts[2]). split gives every part as a string; when "2.5" is compared with 0, the program stops with a TypeError. The details are in the "Common mistake" section below. The second is forgetting to make the text lowercase. If "LOAD GC-01 2.50" is not made lowercase, the first word is "LOAD", which is not equal to "load", and the command is rejected as Unknown command. For Python, uppercase and lowercase letters are different characters.
In both cases, tests help you: one assert that tries a command with capital letters and another that tries a numeric amount catch these mistakes before the project is finished. Do the same in the project steps: after finishing each step, write at least one test for the function of that step, then go on to the next step.
The three patterns and the command parser together: first the tests run, then the state is reset and the cashier's commands are processed.
cards = {}
def reset():
cards.clear()
cards.update({"GC-01": 5.00, "GC-02": 0.00})
def check_card(code, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if code not in cards:
raise ValueError(f"Card not found: {code}")
def load(code, amount):
check_card(code, amount)
cards[code] += amount
return cards[code]
def spend(code, amount):
check_card(code, amount)
if amount > cards[code]:
raise ValueError(f"Insufficient balance: ${cards[code]:.2f} available")
cards[code] -= amount
return cards[code]
def command(text):
parts = text.lower().split()
if len(parts) == 3 and parts[0] == "load":
return load(parts[1].upper(), float(parts[2]))
elif len(parts) == 3 and parts[0] == "spend":
spend(parts[1].upper(), (parts[2]))
:
ValueError(f)
run_tests():
reset()
load(, 2.50) == 2.5,
spend(, 1.50) == 3.5,
command() == 2.5,
:
spend(, 2.75)
,
ValueError:
cards[] == 2.5,
:
command()
,
ValueError:
reset()
()
run_tests()
reset()
text [, , , ]:
:
(f)
ValueError error:
(f)Leaving the number in the command as a string. split gives every part as a string. If you pass the amount to the function without converting it, the first check crashes:
cards = {"GC-01": 5.00}
def load(code, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
cards[code] += amount
return cards[code]
parts = "load GC-01 2.50".split()
print(load(parts[1], parts[2]))Error:
OutputTypeError: '<=' not supported between instances of 'str' and 'int'The message says "the <= operator cannot be used between a string and an integer": in the amount box there is not the number 2.50 but the string "2.50". Although the error appears on a line inside load, the problem is on the line that calls it. The correct version: load(parts[1], float(parts[2])).
reset() returns it to its starting values in place with clear and update, so every cell and every test starts from the same point.ValueError if one is broken, and changes the state only after that; raise does not undo a change made earlier.try + operation + assert False + except ValueError: pass, and that the state did not change after the rejection is checked with a separate assert; the minimum requirement of the final project is at least 3 functions and at least 1 assert for each of them.Next lesson: none; the next stop is the project you choose (Mini bank or Adventure game). Choose your project and finish it step by step; when you finish, you know enough Python basics to take a program from the request all the way to the tests by yourself.
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.
OutputAll tests passed
> load GC-02 2.50 => 2.5
> SPEND gc-02 1.00 => 1.5
> spend GC-02 4.50 => Error: Insufficient balance: $1.50 available
> dance now => Error: Unknown command: dance nowAs in lesson 39, the skeleton comes first: every function in the function list, with its name, parameters, and a one-line description. A function whose body is only a description runs and returns None; in the project steps you will fill in the bodies one by one.
accounts = {}
def find_account(number):
"""Returns the account if it exists; otherwise raises ValueError."""
def check_amount(amount):
"""Raises ValueError if the amount is zero or negative."""
def deposit(number, amount):
"""Checks first, then increases the balance; returns the new balance."""
def withdraw(number, amount):
"""Checks first (including insufficient balance), then decreases the balance."""
def transfer(source, target, amount):
"""Does not touch any balance until both accounts have been found."""
def run_tests():
"""Tests each function with at least one assert."""
print(deposit("A-1003", 20.00))OutputNoneThe same method in the game: four functions and a test function. Each rule is written in the description of a function; a test that expects an error will come for each rule.
rooms = {}
player = {}
def look():
"""Returns the text that describes the player's room; the cellar is dark without the lantern."""
def go(direction):
"""Raises ValueError if there is no exit or the door is locked; otherwise moves the player."""
def take(item):
"""Raises ValueError if the room is dark or the item is not there; otherwise adds it to the inventory."""
def command(text):
"""Makes the text lowercase and splits it, then calls look, go, or take by the first word."""
def run_tests():
"""Tests the rules, including the locked door, with assert."""
print(command("go north"))OutputNoneWarning
Forgetting to make the text lowercase gives no error message; it quietly goes to the wrong branch: if "LOAD GC-01 2.50" is not made lowercase, the first word does not match "load" and the command is rejected as Unknown command: LOAD GC-01 2.50. Let the first line of the parser always be parts = text.lower().split(); when you look the card code up in the dictionary, make it uppercase again with upper().