←
Class 12 Computer Science
13. Project Based Learning · 13 / 13
⌕
Chapter 13 of 13

13. Project Based Learning

5 sections · 7,152 words

Opening

705 words · 3 min read

Big idea: A project is complete when someone else can use it, understand it and check that it works.

Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.

  • Turn a problem into a small testable specification.
  • Separate modules and agree on their interfaces.
  • Work as a team and record evidence of testing.
  • Build a tested automation, puzzle or learning game from an original specification.
  • Keep a project report that another person can repeat.

Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.

This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.

The school library keeps its records in a worn register. New books are squeezed into margins.

A crossed-out issue entry is unreadable. Two helpers disagree about whether one popular title is on the shelf or with a reader.

Nothing is broken except the system for knowing the truth. This chapter builds a small program that replaces that register.

A second picture helps too. A marks sheet travels from teacher to teacher.

Each copy adds a column in a different order. Nobody can say which copy is current.

A shared file with clear rules would end the argument. The same building skills solve both problems.

The chapter builds in five stages. First it turns a vague wish into acceptance tests.

Then it splits the work into modules with clear interfaces. Then it organises teamwork and test evidence.

Then it constructs the library manager feature by feature, with every stage run and traced. Last it offers three further project descriptions and a report format.

One running example ties the stages together. A school library needs to add books, list them, search by title word, issue books to readers, accept returns, and keep records in a file.

Each section adds one layer: the specification, the module design, the test evidence, then the working code.

Study by predicting. Cover each result line and each expected output before reading it.

Say the answer aloud first. When a prediction fails, find the first line where your trace diverged.

That line holds the lesson. Short sentences carry one idea each.

Expect the same vocabulary in every section. Requirement, constraint, acceptance test, module, interface, milestone and regression keep one meaning throughout.

Technical words are defined in plain words at first use. When a sentence confuses you, check which term it uses.

A common early mistake is collecting features instead of evidence. A long menu with untested buttons teaches less than three buttons with passing tests. Each section asks what you can demonstrate, not what you can name.

Worked examples follow one pattern: goal, approach, trace, result. Read the goal before the steps. Trace each step against the table or the diagram. State the result in your own words before reading it.

Diagrams in this chapter are checklists, not decoration. Cover the caption and explain the arrows first.

Then read the walkthrough and check your explanation. Steps that you can repeat from memory are steps you can use in your own project.

StageQuestion it answers
13.1 SpecificationHow will we recognise success and failure.
13.2 ModulesWhich part does what, and what values cross each boundary.
13.3 TeamworkWho does what next, and what evidence proves it works.
13.4 ConstructionHow does the running program grow without breaking earlier work.

Read the table as a map of the chapter. Specification decides the finish line.

Modules divide the walk. Teamwork shares the load.

Construction takes the steps in order. Skip the first row and the later rows have no direction.

A finished project is not a large file. It is a small system whose behaviour another person can repeat, check and trust.

Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.

13.1 INTRODUCTION

1,026 words · 5 min read

A project is a small solution to a stated need. A menu that opens is only evidence that the menu opens. It does not prove that data are saved correctly or that invalid requests leave good records intact.

An acceptance test makes success visible. It describes an input or action and an expected observation. That lets another person judge the result without relying only on the author’s confidence.

  1. Describe the intended user and main task.
  2. Write observable success and failure examples.
  3. Build the smallest complete workflow that meets them.
In simple words: A small reliable result is a stronger project than a long list of unfinished promises.

A project succeeds when its result can be checked, not when its menu merely opens.

A school helper keeps marks in a notebook with no page numbers. Asked for one record, the helper flips pages for a minute.

Asked whether the numbers are final, the helper shrugs. The data may be correct, but nobody can check it.

That gap between having data and proving correctness is what this section closes.

Project based learning uses a concrete problem to organise investigation, design, implementation and reflection. The aim is not simply a large source file.

The result should meet a stated need and provide evidence that its essential behaviour works.

A requirement describes needed behaviour. A constraint limits the solution, such as available time or a required file format.

An acceptance test describes an observable result that demonstrates a requirement. Decide these before spending time on decoration.

Vague wishTestable version
Make it easyA new user can complete the main task from labelled controls and a short instruction.
Keep data safeA failed validation leaves existing records unchanged.
Make it fastThe agreed representative dataset completes within a stated measured limit on the chosen machine.
Save everythingAfter a normal restart, the documented persistent records can be reloaded correctly.

Read the table row by row. Each vague wish becomes an observation a stranger could repeat.

Easy means a new user finishes the task. Safe means failure changes nothing.

Fast names a dataset and a machine. Saved means records survive a restart.

Testable wording turns argument into measurement.

Write the library specification the same way. The user is the teacher in charge of the school library.

The main tasks are adding books, listing them, searching by title word, issuing books and accepting returns. The constraint is plain Python with one data file, finished in 6 working sessions: 2 for design, 3 for building, 1 for testing.

Count the sessions openly: 2 + 3 = 5, then 5 + 1 = 6. Six sessions force a small scope.

A team that plans ten features for six sessions has planned a failure. A team that plans four tested features has planned a demonstration.

Name the user and taskWrite acceptance examplesDesign small modulesBuild one thin sliceTest, document, review
A project pipeline from a stated need to a checked result.

Read the diagram from top to bottom. Naming the user and task stops the project from drifting.

Acceptance examples make success visible before code exists. Small modules divide the work.

One thin slice proves the approach early. Testing, documentation and review close every loop.

Each arrow means the earlier box is written down, not merely discussed.

Acceptance caseExpected observation
Add a valid bookThe catalogue grows from 3 records to 4.
Add a duplicate idThe request fails and the original record is unchanged.
Search the word mapThe two matching ids are returned.
Issue a free bookThe reader tag is recorded on that book.
Issue the same book againThe request fails and the first reader tag remains.
Reload saved recordsThe same ids, titles and reader tags return.

Read the table as the library contract. Adding grows the count from 3 to 4.

A duplicate changes nothing. Searching finds both matching titles.

Issuing records the reader, and a second issue is refused without touching the first record. Reloading restores everything the team saved.

Notice what the table leaves out. It says nothing about colours, fonts or extra features.

Decoration can wait until the contract passes. A reliable core with clear limitations teaches more than many half-working features.

Record limitations honestly rather than changing the requirement silently after a failed test.

A team says its app “works” because the main menu opens. What evidence is missing?

The menu is only an entry point. Requirements concern the outcomes of the actions behind it.

Result: Demonstrate the main workflow, validation failures, saved-state recovery and boundary cases.

A library helper proposes “fast search” as a requirement. Rewrite it as an acceptance test.

Goal. Turn a vague speed wish into an observable check.

Approach. Name the dataset, the machine and the measured limit.

Trace. “Fast” names no input and no limit, so two testers can disagree forever. A dataset of 12 records on the classroom machine with a stated second limit gives one repeatable observation.

Result. “Searching 12 records on the classroom machine completes within the stated limit.”.

Result: One dataset, one machine, one limit: that is what makes speed testable.

Success is an observation a stranger can repeat. Write the observation before writing the program.

Copy each acceptance case onto a card or a checklist. Tick it only when you have seen the behaviour with your own eyes.
Common mistake: Code that launches is not automatically a completed project.

⚡ Quick Check Flashcards4 questions
Question 1
What connects a requirement to evidence?
Try answering before revealing!
Question 2
Why define constraints early?
Try answering before revealing!
Question 3
Why does the library plan allow only four tested features?
Try answering before revealing!
Question 4
What must a duplicate-book request leave behind?
Try answering before revealing!

13.2 APPROACHES FOR SOLVING PROJECTS

1,025 words · 5 min read

A module should have one understandable responsibility. Input parsing, task rules, storage and presentation can be tested separately when their interfaces clearly state what values they exchange.

Starting from the whole task helps you avoid missing a necessary stage. Building a tested small component helps you learn what the implementation requires. A project can combine both directions.

  1. Draw the end-to-end workflow.
  2. Give each module an input, output and failure rule.
  3. Integrate one thin working slice before extending the design.
In simple words: Good boundaries reduce the amount of code you must understand at once.

A large task becomes manageable when each part owns one responsibility.

The library register mixes everything together. Titles, reader names and due notes share one crowded page.

One correction smudges three facts. Splitting the page into labelled columns would already help.

Splitting a program into modules helps in the same way.

A modular approach separates responsibilities. A top-down approach starts from the whole workflow and refines it into smaller tasks.

A bottom-up approach builds tested components and combines them. A practical project can use both rather than treating them as exclusive choices.

Start from the top to avoid missing a stage: a library without returns handling is incomplete. Build from the bottom to learn what the code requires: a tested add function teaches the record shape.

The two directions meet at the interface agreements.

ModuleResponsibilityExample interface
InputCollect and parse a requestReturn a validated request or a clear error.
Domain logicApply task rulesreserve(device_id, slot_id).
StoragePersist and retrieve recordsload_state and save_state.
PresentationExplain results to the userShow success or a specific failure.
TestingCheck expected behaviourVerify state and output for known cases.

Read the table row by row. Input guards the door. Domain logic applies the rules. Storage remembers. Presentation explains. Testing verifies. Each row names one job so that a defect can be traced to one address.

An interface is an agreement about input, output and failure behaviour. Write down field names and types, valid ranges and whether a function changes supplied data.

Teams can work separately only when those agreements are consistent.

Library moduleOwnsInterface promise
Catalogue rulesRecord shape and id uniquenessadd_book rejects blank fields and duplicate ids with ValueError.
SearchTitle-word matchingfind_books returns a list of matching ids, never half a record.
LoansIssue and return stateissue_book refuses an issued book; return_book refuses a free book.
StorageFile saving and loadingsave_state writes JSON; load_state validates before adopting.
ReportsCounts and listsavailable_books counts records whose reader tag is empty.

Read the table as five contracts. Catalogue rules protect identity.

Search returns whole answers. Loans protect the holder.

Storage validates before adopting. Reports count from the same records everyone shares.

When two modules disagree, this table names the rule that settles it.

Plan milestones with visible results: a core function, one working user flow, persistence, failure handling, then refinement. Reassess estimates after the first slice.

Keep a record of decisions and unresolved questions.

Skeleton: add plus listSearch by title wordIssue and return booksSave and reload a fileRun the test checklist
Each slice adds one behaviour while earlier tests keep passing.

Read the diagram as the build order for the library. The skeleton proves add and list first.

Search arrives second on tested records. Loans arrive third on tested search results.

The file layer arrives fourth without changing the rules. The checklist runs last and must stay green after every later change.

Earlier boxes are promises the later boxes must keep.

Apply both directions to one feature to feel the difference. Top-down splits “reload saved records” into open the file, parse the text, validate each record, then adopt the catalogue.

No stage can hide because the whole workflow is visible first. Bottom-up builds the record validator alone, testing it on one good and one bad record before any file code exists.

The validator is then trusted when the file layer arrives.

The library uses both. The acceptance table gives the top-down workflow.

Stages 1 to 5 build bottom-up components that the checklist then joins. When a slice fails, the split says whether the workflow missed a stage or a component broke its promise.

Two modules use different meanings for an empty string. What should change?

The interface leaves missing data ambiguous. Both modules need the same representation and validation rule.

Result: Define the rule centrally and test both sides before integration.

Split “issue a book to a reader” across the library modules.

Goal. Give each module exactly one job for one loan.

Approach. Walk the request from typing to storage using the module table.

Trace. Input collects the book id and reader tag and rejects blanks. Catalogue rules confirm the id exists. Loans checks the reader tag is empty, then records the new tag. Storage saves the updated catalogue. Presentation shows the success and the new holder.

Result. Five modules, one rule each, no shared guesswork.

Result: When a loan fails, this split says which module must explain why.

Good boundaries reduce the amount of code you must understand at once. Write the boundary before writing the code.

Draw the modules as boxes and label every arrow with the exact value it carries. An unlabeled arrow is a future integration bug.
Common mistake: Splitting files is not enough; modules need clear responsibilities and compatible interfaces.

⚡ Quick Check Flashcards4 questions
Question 1
What does top-down design start from?
Try answering before revealing!
Question 2
Why integrate early?
Try answering before revealing!
Question 3
Which library module decides a duplicate id?
Try answering before revealing!
Question 4
What does a milestone demonstrate?
Try answering before revealing!

13.3 TEAMWORK

1,036 words · 5 min read

Teamwork is easier when each task has an owner and a clear result. Other members need to know what changed, how to use it and what still needs attention.

Review and shared tests make integration a team responsibility. When a combined system fails, inspect the exchanged values and interface agreement instead of treating the problem as somebody else’s isolated part.

  1. Agree on the next concrete result and who owns it.
  2. Share small changes with an explanation and test evidence.
  3. Review the combined behaviour and record unresolved decisions.
In simple words: Respectful collaboration makes defects easier to discuss and shared knowledge easier to retain.

A team finishes when each person knows the next concrete result they own.

Three students share one library program. One edits the search while another renames its function.

The program breaks and each blames the other. The missing piece is not skill.

It is an agreement about who changes what, and a test that catches the clash.

BehaviourConcrete practice
CommunicateReport what changed, what is blocked and what help is needed.
ListenRestate another member’s proposal before evaluating it.
ShareUse one agreed source repository and explain new interfaces.
RespectCritique the change and its evidence rather than the person.
HelpPair on an unfamiliar task instead of silently taking over.
ParticipateComplete agreed work and make progress visible.

Read the table as six daily habits. Reporting keeps blockers visible.

Restating prevents rushed judgement. Sharing one source stops parallel universes.

Critiquing the change keeps people safe. Pairing spreads skill.

Visible progress replaces status meetings.

Give each task an owner, a result and a review partner. Rotate roles so one person does not hold all knowledge of storage, testing or the user interface.

A coordinator keeps dependencies visible; coordination does not make that person the only decision-maker.

Use small changes and meaningful version history. Before combining work, review what changed and run relevant tests. Preserve a working version so a failed experiment does not destroy the last known good state.

Owner finishes one slicePartner reviews the changeRun the shared testsRecord each decision
A review loop that keeps shared work understandable.

Read the diagram as one working loop. The owner builds a small slice and says what changed.

The partner reads the change against the interface table. The shared tests run before combining.

Decisions and open questions are written down the same day. A loop that takes an hour beats a review that waits a week.

Testing supplies the evidence the report will need. The library team keeps a table of cases with expected and observed results.

Every entry is replayed after each change, so a repair in one module cannot silently break another.

Test caseExpected resultObserved result
Add a valid bookCatalogue grows to 4 records.Count 4 as printed.
Add a duplicate idRejected; catalogue stays at 4.Rejection message; count unchanged.
Search the word mapIds of the 2 matching titles.Both ids returned in order.
Issue a free bookReader tag recorded.Tag present on that record.
Issue it againRejected; first tag kept.Rejection message; holder unchanged.
Save and reloadSame records return.Equal catalogues after reload.

Read the table across each row. The middle column states the promise from the specification.

The right column records what the run actually showed. A row is done only when both columns agree.

Numbers come from real runs: the catalogue grows to 4, and search returns 2 ids.

Keep a bug log beside the test table. One honest row teaches more than a perfect-looking report.

SymptomCauseRepairRegression check
Searching map returns no idsCompared raw input against mixed-case titlesLowercase both sides and strip spacesSearch map, Map and spaced MAP all find both titles.

Read the log as a closed story. The symptom is what the user saw.

The cause names the faulty assumption. The repair changes the code, not the test.

The regression check keeps the defect from returning. Section 13.4 runs this exact story.

One member says “my part works” while the combined app fails. How should the team respond?

Reproduce the combined failure, inspect the interface agreement and reduce it to the smallest failing exchange.

Result: Treat integration as shared work. Assign a focused repair and add a regression check for the actual failure.

A teammate reports that searching map misses “Stars and Maps”. What is the first check?

Goal. Decide whether the defect sits in the data or in the matching rule.

Approach. Reproduce with one known record before reading the code.

Trace. The record exists with a capital M in Maps. The query uses a small m in map. A direct substring test is case sensitive, so the pair cannot match. The data are correct; the rule ignores case differences.

Result. Suspect the matching rule, then confirm with the smallest failing exchange.

Result: Reproduce first, blame no module, then read the rule that the failing exchange exercises.

A final handover should include installation steps, sample input, the expected output, known limits and test evidence. Another team should be able to repeat the main demonstration without the authors explaining every click.

Visible progress plus shared tests turns three private efforts into one checked result.

When the combined program fails, write down the smallest failing exchange before changing any code. Small reproductions find causes; large guesses hide them.
Common mistake: “Everyone owns it” should not mean nobody owns the next concrete task.

⚡ Quick Check Flashcards4 questions
Question 1
Why rotate responsibilities?
Try answering before revealing!
Question 2
What makes feedback useful?
Try answering before revealing!
Question 3
Why replay all tests after each repair?
Try answering before revealing!
Question 4
What does one bug-log row contain?
Try answering before revealing!

13.4 PROJECT DESCRIPTIONS

3,360 words · 15 min read

The project descriptions below separate rules from menus and file handling. This lets you understand the essential state change before adding more interface code.

A reservation must preserve an earlier accepted booking when a duplicate is rejected. A puzzle move must change only the permitted neighbours. A learning game must explain the answer rather than merely display a score.

  1. Choose one project and copy its acceptance cases into your plan.
  2. Run its small core and explain each state change.
  3. Add storage and presentation while keeping those cases passing.
In simple words: Treat each new feature as another behaviour to explain and test, not simply another block of code.

This section constructs the library manager in five slices. Each slice is a complete runnable program with its trace.

Later slices reuse the tested functions without changing their promises. Read each stage in order and predict every output before reading on.

Every project starts with its smallest checkable behaviour. For the library that means adding a book and counting the catalogue.

Records are dictionaries with three string fields: id, title and issued_to. An empty reader tag means the book is on the shelf.

Cover the output box and say what the program should print before reading on.

catalogue = []

def add_book(catalogue, book_id, title):
    if not book_id.strip() or not title.strip():
        raise ValueError("missing field")
    for book in catalogue:
        if book["id"] == book_id:
            raise ValueError("duplicate id")
    catalogue.append({"id": book_id, "title": title, "issued_to": ""})
    return len(catalogue)

print(add_book(catalogue, "B1", "Logic Puzzles"))
print(add_book(catalogue, "B2", "Stars and Maps"))
print(len(catalogue))
print(catalogue[0]["title"])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The catalogue starts empty, so the first add has nothing to clash with.
  2. Each call strips its fields first, so blank ids and blank titles are rejected before any loop runs.
  3. The loop compares the new id against every stored id, which enforces uniqueness one record at a time.
  4. Append stores a dictionary with an empty reader tag, meaning on the shelf.
  5. Return gives the new length, so the two prints show 1 then 2 and the final prints confirm the count and the first title.

Output
1
2
2
Logic Puzzles

Add a book with a duplicate id inside try and except. Predict the message and the unchanged length before running.

Read the program again. The first print shows 1 because one record now exists.

The second shows 2 because two records exist. The third confirms the count, and the fourth reads back the stored title.

Validation happens before mutation: a rejected call never reaches append.

Listing helps when the catalogue is tiny. Searching helps when it grows.

The rule is simple: lowercase both the query and each title, then keep the ids that contain the query. Lowercasing both sides is the repair from the bug log, built in from the start.

Predict each printed line first. The trace below explains every one.

catalogue = [
    {"id": "B1", "title": "Logic Puzzles", "issued_to": ""},
    {"id": "B2", "title": "Stars and Maps", "issued_to": ""},
    {"id": "B3", "title": "Map Skills", "issued_to": ""},
]

def find_books(catalogue, word):
    cleaned = word.strip().lower()
    if not cleaned:
        raise ValueError("missing field")
    found = []
    for book in catalogue:
        if cleaned in book["title"].lower():
            found.append(book["id"])
    return found

print(find_books(catalogue, "map"))
print(len(find_books(catalogue, "map")))
print(find_books(catalogue, "chess"))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Three records give the search something realistic to scan.
  2. Strip removes surrounding spaces and lower unifies the case, so spaced or capitalised queries behave identically.
  3. An empty query raises an error instead of matching everything, which would be a misleading answer.
  4. The loop tests each title and collects only ids, so the caller never receives half a record.
  5. Map appears in two titles and chess in none, which explains the three printed lines.

Output
['B2', 'B3']
2
[]

Search for " MAP " with spaces and capitals. Predict the result before running.

Read the result carefully. Both matching ids appear in catalogue order.

The count print shows 2. An empty list is a correct answer, not a failure: it means no title matched.

Returning ids rather than full records keeps the interface narrow.

Loans change exactly one field: the reader tag. Issuing writes the tag when it is empty.

Returning clears it when it is set. Every other path raises an error and touches nothing.

Trace how the failed second issue leaves the first holder in place.

Say the result in your own words before checking it against the output box.

catalogue = [{"id": "B1", "title": "Logic Puzzles", "issued_to": ""}]

def issue_book(catalogue, book_id, reader):
    if not reader.strip():
        raise ValueError("missing field")
    for book in catalogue:
        if book["id"] == book_id:
            if book["issued_to"] != "":
                raise ValueError("already issued")
            book["issued_to"] = reader.strip()
            return book["issued_to"]
    raise ValueError("unknown book")

def return_book(catalogue, book_id):
    for book in catalogue:
        if book["id"] == book_id:
            if book["issued_to"] == "":
                raise ValueError("not issued")
            book["issued_to"] = ""
            return True
    raise ValueError("unknown book")

print(issue_book(catalogue, "B1", "Reader A"))
try:
    issue_book(catalogue, "B1", "Reader B")
except ValueError as error:
    print(error)
print(return_book(catalogue, "B1"))
print(catalogue[0]["issued_to"] == "")

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. A blank reader tag is rejected before any record is touched.
  2. The loop finds B1 with an empty tag, writes the stripped reader name and returns it.
  3. The second issue finds the same record with a non-empty tag, so raise fires before any assignment.
  4. Return finds the issued record, clears the tag and reports True.
  5. The final comparison confirms the tag is empty again, closing the loan cleanly.

Output
Reader A
already issued
True
True

Issue an unknown id such as B9. Predict which error message appears before running.

This stage proves the acceptance promise: a rejected double issue keeps the first holder. The error message names the problem, and the stored record still says Reader A until the return clears it. Never let a failed request partly change the data it claims to reject.

Memory forgets when the program ends, so records move to a file. The program converts the catalogue to JSON text when saving and rebuilds it when loading.

Loading validates every record in a temporary value before adopting it, so a damaged file cannot destroy the good catalogue.

FieldTypeRule
idStringNon-blank and unique within the file.
titleStringNon-blank descriptive text.
issued_toStringEmpty means on the shelf; otherwise the holder tag.

Read the table as the file contract. Three string fields, no missing keys, no invented types.

Any record that breaks these rules fails the whole load, and the running catalogue stays untouched. That all-or-nothing adoption is the persistence half of “keep data safe”.

Read the code once without the trace, then use the trace to check yourself.

import json

def save_state(path, catalogue):
    with open(path, "w", encoding="utf-8") as stream:
        json.dump(catalogue, stream)

def load_state(path):
    try:
        with open(path, "r", encoding="utf-8") as stream:
            data = json.load(stream)
    except FileNotFoundError:
        return []
    if not isinstance(data, list):
        raise ValueError("bad file")
    for book in data:
        if not isinstance(book, dict):
            raise ValueError("bad file")
        for field in ("id", "title", "issued_to"):
            if field not in book or not isinstance(book[field], str):
                raise ValueError("bad file")
    return data

catalogue = [{"id": "B1", "title": "Logic Puzzles", "issued_to": "Reader A"}]
save_state("library.json", catalogue)
loaded = load_state("library.json")
print(len(loaded))
print(loaded[0]["issued_to"])
print(loaded == catalogue)
print(load_state("missing.json"))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The import loads the standard JSON converter used for the file format.
  2. Save opens the file for writing and stores the whole catalogue as structured text.
  3. Load opens the same file for reading and parses it back into Python values.
  4. A missing file is a normal first run, so the handler returns an empty catalogue instead of crashing.
  5. Non-list content, non-record entries and wrong field types each raise one clear error.
  6. The prints confirm one reloaded record, its holder tag, equality with the original and the empty first-run catalogue.

Output
1
Reader A
True
[]

Corrupt the file with one line of plain text and reload. Predict whether the old catalogue survives before running.

Read the program again. The equality print shows True because every field survived the round trip.

The missing-file print shows an empty list, which lets a fresh installation start cleanly. File examples use an external Python playground because the in-browser tutor has no ordinary file access; copy the complete example before opening it.

The last slice gathers every rule into one replayable test. A tiny check helper compares each result with its expectation and counts passes.

Six checks cover adding, duplicates, search, issuing, double issue and the available count. One run proves the whole catalogue still behaves.

Cover the output box and say what the program should print before reading on.

catalogue = [
    {"id": "B1", "title": "Logic Puzzles", "issued_to": ""},
    {"id": "B2", "title": "Stars and Maps", "issued_to": ""},
    {"id": "B3", "title": "Map Skills", "issued_to": "Reader A"},
]

def add_book(catalogue, book_id, title):
    if not book_id.strip() or not title.strip():
        raise ValueError("missing field")
    for book in catalogue:
        if book["id"] == book_id:
            raise ValueError("duplicate id")
    catalogue.append({"id": book_id, "title": title, "issued_to": ""})
    return len(catalogue)

def find_books(catalogue, word):
    cleaned = word.strip().lower()
    if not cleaned:
        raise ValueError("missing field")
    return [b["id"] for b in catalogue if cleaned in b["title"].lower()]

def issue_book(catalogue, book_id, reader):
    for book in catalogue:
        if book["id"] == book_id:
            if book["issued_to"] != "":
                raise ValueError("already issued")
            book["issued_to"] = reader.strip()
            return book["issued_to"]
    raise ValueError("unknown book")

passed = 0
failed = 0

def check(name, got, want):
    global passed, failed
    if got == want:
        passed = passed + 1
        print("PASS " + name)
    else:
        failed = failed + 1
        print("FAIL " + name)

check("add valid", add_book(catalogue, "B4", "Number Games"), 4)
try:
    add_book(catalogue, "B4", "Other Title")
    check("duplicate rejected", "kept", "rejected")
except ValueError:
    check("duplicate rejected", len(catalogue), 4)
check("search map", find_books(catalogue, "map"), ["B2", "B3"])
check("issue B1", issue_book(catalogue, "B1", "Reader B"), "Reader B")
try:
    issue_book(catalogue, "B1", "Reader C")
    check("double issue rejected", "kept", "rejected")
except ValueError:
    check("double issue rejected", catalogue[0]["issued_to"], "Reader B")
check("available count", len([b for b in catalogue if b["issued_to"] == ""]), 2)
print("passed " + str(passed) + " of " + str(passed + failed))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Three starting records set up the exact states the checks need.
  2. The helper prints PASS with the check name on equality and FAIL otherwise, counting both.
  3. Adding B4 grows the catalogue to four, which the first check confirms.
  4. The duplicate attempt raises before append, so the count stays at four.
  5. Search returns both matching ids in order, and issuing records the new holder.
  6. The double issue raises, so the stored holder is still Reader B.
  7. Two records have empty tags, and the summary line reports six passes out of six.

Output
PASS add valid
PASS duplicate rejected
PASS search map
PASS issue B1
PASS double issue rejected
PASS available count
passed 6 of 6

Break one rule on purpose, for example by removing lower from search. Predict which check fails before running.

Read the summary line last. It reports passed 6 of 6. Six green rows mean the specification table from section 13.1 now has running proof. Keep this checklist and replay it after every future change.

Early in testing, the search looked like this. The query was stripped but never lowercased, and titles kept their capitals.

Searching map found nothing, though two titles contain the word. The test table caught it because the expected row said two ids and the observed row said none.

Predict each printed line first. The trace below explains every one.

catalogue = [
    {"id": "B1", "title": "Logic Puzzles", "issued_to": ""},
    {"id": "B2", "title": "Stars and Maps", "issued_to": ""},
]

def find_books(catalogue, word):
    cleaned = word.strip()
    if not cleaned:
        raise ValueError("missing field")
    found = []
    for book in catalogue:
        if cleaned in book["title"]:
            found.append(book["id"])
    return found

print(find_books(catalogue, "map"))
print(find_books(catalogue, "Map"))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Two records set up a case the spelling almost hides.
  2. Strip without lower leaves the capital M in Maps and the small m in map unmatched.
  3. The loop compares raw text, so only the exactly matching capital query finds anything.
  4. The prints show the defect plainly: zero ids for map against one for Map.

Output
[]
['B2']

Try "MAP" in capitals before reading on. Predict whether it matches anything.

The repair lowercases both sides, exactly as stage 2 shows. The regression check searches map, Map and a spaced capital MAP, and all three now return the same id.

Count the lesson: 0 ids before the repair, 1 after, in this two-book demo. Log the row in the bug table and move on.

The library above is the worked path. Now choose one of the following original projects for your own team.

Begin with a command-line version and a small documented file format. Add a graphical interface only after the core behaviour and persistence work.

A study group shares devices in labelled time slots. A reservation is identified by the pair device_id and slot_id.

The system lists available choices, creates a reservation, cancels an existing reservation and saves its state for a later session.

  • Store a device catalogue with stable identifiers.
  • Reject an unknown device, blank slot or duplicate device-and-slot reservation.
  • Keep an account tag with each accepted reservation.
  • Show a sorted list of reservations without using display position as identity.
  • Make a failed request leave existing state unchanged.
  • Document a persistence format and validate it when loading.

The following core deliberately uses an in-memory dictionary so that the rule can be tested independently of menus and files. Its fields are strings, and the supplied dictionaries must follow that contract.

Predict the output before running this complete example.

def reserve(devices, bookings, device_id, slot_id, account_tag):
    if device_id not in devices:
        raise ValueError("unknown device")
    if not slot_id.strip() or not account_tag.strip():
        raise ValueError("missing field")
    key = (device_id, slot_id)
    if key in bookings:
        raise ValueError("already reserved")
    bookings[key] = account_tag

devices = {"device P", "device Q"}
bookings = {}
reserve(devices, bookings, "device P", "slot A", "account A")
try:
    reserve(devices, bookings, "device P", "slot A", "account B")
except ValueError as error:
    print(error)
print(len(bookings))
print(bookings[("device P", "slot A")])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The function validates the device and required text before changing bookings.
  2. The pair of device and slot forms the reservation key.
  3. A repeated key raises an error before an assignment can overwrite the earlier account.
  4. The final prints confirm that rejection kept the accepted reservation intact.

Output
already reserved
1
account A

Reserve the other device in the same slot and explain why that pair is different.

For JSON persistence, represent each tuple-key reservation as an explicit record with named fields; JSON object keys are not Python tuple keys. Load into a fresh temporary state, validate the whole input, then adopt it.

This avoids partially importing a malformed file.

Acceptance caseExpected observation
Reserve a free pairOne new record appears.
Reserve the same pair againRequest fails and the original account tag remains.
Cancel a missing pairA documented clear response; no unrelated deletion.
Reload saved valid recordsThe same reservation identities and values return.
Load malformed recordsNo partial overwrite of the accepted state.

Present a short sequence of distinct labelled tokens. A move swaps two adjacent positions.

The player must reach a target order using as few moves as possible. Use a deterministic starting state first, so tests do not depend on random chance.

Separate state, legal-move validation, move application, goal testing and display. Count only accepted moves.

A rejected move must leave both the sequence and the move count unchanged. Decide whether undo is included; if it is, a stack of previous states gives a useful design exercise.

Predict the output before running this complete example.

def swap_neighbours(tokens, left):
    if not isinstance(left, int) or isinstance(left, bool):
        raise ValueError("index must be an integer")
    if left < 0 or left + 1 >= len(tokens):
        raise ValueError("invalid move")
    result = tokens.copy()
    result[left], result[left + 1] = result[left + 1], result[left]
    return result

state = ["C", "A", "B"]
state = swap_neighbours(state, 0)
state = swap_neighbours(state, 1)
print(state)
print(state == ["A", "B", "C"])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The first checks reject an unsuitable index or a move beyond either end.
  2. Copy creates a new state, leaving the supplied state available unchanged.
  3. The simultaneous assignment exchanges only the adjacent pair.
  4. The goal test compares the resulting order with the target sequence.

Output
['A', 'B', 'C']
True

Try an out-of-range move and verify that the original sequence still exists unchanged.

For distinct target-ranked tokens, the inversion count measures how many pairs are in the wrong relative order. An adjacent swap changes that count by one, so it provides a lower bound on the moves needed; sorting by correcting adjacent inversions can achieve it.

If repeated tokens are allowed, define identity and goal matching more carefully.

Acceptance caseExpected observation
Leftmost and rightmost legal swapsExactly the chosen neighbours exchange places.
Out-of-range moveClear error; original state unchanged.
Already solved stateCompletion detected without requiring an extra move.
Undo, if includedThe previous state returns under the documented move-count rule.

Create a short practice game about bytes, bits and ideal transfer time. Each round supplies a byte count and a bit rate.

The learner enters a time in seconds. The program checks units, compares with a tolerance and explains the calculation.

Separate question generation from answer checking. Use a fixed set of cases first; add randomness only after the deterministic version is tested.

Keep the tolerance relative to the answer scale, and reject non-finite input so an invalid numeric value cannot accidentally pass.

Predict the output before running this complete example.

import math

def expected_seconds(byte_count, bit_rate):
    if byte_count < 0 or bit_rate <= 0:
        raise ValueError("invalid transfer data")
    return byte_count * 8 / bit_rate

def correct(answer, expected):
    return math.isfinite(answer) and math.isclose(
        answer, expected, rel_tol=0.01, abs_tol=0.001)

expected = expected_seconds(1800000, 3600000)
print(expected)
print(correct(4.0, expected))
print(correct(float("nan"), expected))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The first function validates the question data, then converts bytes to bits before dividing by the bit rate.
  2. The second function rejects a non-finite answer before applying a tolerance comparison.
  3. The example includes a valid answer and a non-number value to demonstrate both paths.

Output
4.0
True
False

Supply a nearby finite answer and then a clearly different one. Explain the role of the tolerance.

This calculation excludes setup time, headers and retransmissions. Display that assumption beside the question.

The game should teach why a result is right, not just award a point. Store only the minimal practice history the learner needs.

Acceptance caseExpected observation
Known exact answerAccepted with a clear explanation.
Answer outside toleranceRejected with the calculated result and unit conversion.
Zero or negative rateQuestion rejected before division.
Non-finite answerRejected.
Reloaded practice historyValid records retained without changing earlier scores.

  • State the problem, intended user and chosen scope.
  • Describe fields, modules and interfaces.
  • Include original code with a clear run procedure.
  • Show acceptance cases with actual and expected results.
  • Explain one defect found and the repair that addressed its cause.
  • Record remaining limits and possible extensions.

Documentation is the part of the project the user actually reads. It needs three pieces: how to run the program, one complete sample session with its exact output, and the known limits.

Write it while the program is small; a long program documented late is documented never.

  1. Install a Python 3 interpreter and copy library.py into a practice folder.
  2. Run the program with the command python3 library.py.
  3. Type the sample inputs in the shown order.
  4. Compare every printed line with the expected output below.
  5. Read the known limits before trusting the program with real records.

Read the list as the stranger’s first five minutes. Installation names the tool.

The run command is exact, not approximate. Sample inputs remove guessing.

Comparison turns reading into checking. Limits prevent misuse.

Each numbered step answers one question a new user would otherwise have to ask the authors.

Output
$ python3 library.py
1
2
2
Logic Puzzles

Read the session line by line. The first line is the typed command.

The next four lines are the printed output of the stage 1 skeleton: two returned lengths, the confirmed count and the first title. A stranger who sees exactly these lines knows the setup works.

Any difference means the installation or the file differs, which is itself useful evidence.

Close with honest limits in plain words. The catalogue lives in one file with no simultaneous users.

Titles match by substring, so short queries can surprise. Records hold only the three documented fields.

Limits are not apologies; they tell the next team where safe extension begins.

  • A testable specification names the user, the task and observable success.
  • Modules divide responsibility; interfaces state inputs, outputs and failures.
  • Teamwork shows in owners, reviews, shared tests and written decisions.
  • Build in thin slices and replay the checklist after every change.
  • Persistence validates before adopting; a failed load keeps the good state.
  • The report lets a stranger repeat the demonstration without the authors.
In simple words: a project is done when the checklist passes, the file reloads, and another person can repeat both.

Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.

13.1 undefined

13.2 undefined

Python
catalogue = [{"id": "B1", "title": "Logic Puzzles", "issued_to": ""}]

def add_book(catalogue, book_id, title):
    if not book_id.strip() or not title.strip():
        raise ValueError("missing field")
    for book in catalogue:
        if book["id"] == book_id:
            raise ValueError("duplicate id")
    catalogue.append({"id": book_id, "title": title, "issued_to": ""})
    return len(catalogue)

try:
    add_book(catalogue, "B9", "   ")
except ValueError as error:
    print(error)
print(len(catalogue))

13.3 undefined

13.4 undefined

13.5 undefined

13.6 undefined

13.7 undefined

13.8 undefined

13.9 undefined

13.10 undefined

13.11 undefined

13.12 undefined

Python
catalogue = [
    {"id": "B1", "title": "Logic Puzzles", "issued_to": "Reader A"},
    {"id": "B2", "title": "Stars and Maps", "issued_to": ""},
]

def available_books(catalogue):
    return [b["id"] for b in catalogue if b["issued_to"] == ""]

print(available_books(catalogue))
print(len(available_books(catalogue)))

13.13 undefined

13.14 undefined

13.15 undefined

13.16 undefined

13.17 undefined

Python
catalogue = [
    {"id": "B1", "title": "Logic Puzzles", "issued_to": "Reader A"},
    {"id": "B2", "title": "Stars and Maps", "issued_to": ""},
]

def remove_book(catalogue, book_id):
    for i in range(len(catalogue)):
        if catalogue[i]["id"] == book_id:
            if catalogue[i]["issued_to"] != "":
                raise ValueError("issued book kept")
            catalogue.pop(i)
            return len(catalogue)
    raise ValueError("unknown book")

print(remove_book(catalogue, "B2"))
try:
    remove_book(catalogue, "B1")
except ValueError as error:
    print(error)
print(len(catalogue))
try:
    remove_book(catalogue, "B9")
except ValueError as error:
    print(error)

13.18 undefined

Answers

13.1 It should show 4. The returned length is the observable evidence that exactly one record was stored; 2 + 1 is shown as one addition, not a guess.

13.2 The lines are “missing field” and 1. Strip turns spaces into an empty title, so validation rejects before append and the catalogue keeps its single record.

13.3 Neither alone identifies a reservation under the stated rule; their combination does.

13.4 “Stars and Maps” and “Map Skills” contain the word after lowercasing; “Logic Puzzles” contains no such substring, so it is correctly excluded.

13.5 The loop that raises “duplicate id” before append guarantees it. Checking after append would store the intruder first, so rejection would leave a corrupted catalogue behind.

13.6 The program raises “unknown book” and stores nothing. The loop finds no matching id, so falling through to raise is the only honest outcome.

13.7 A failed request must not partly perform an action the program reports as rejected.

13.8 Issue B1 then return it twice. The first return prints True; the second raises “not issued” because the tag is already empty.

13.9 Length 1, the holder tag, and equality with the original prove it. A missing file returns an empty list so a fresh setup starts cleanly.

13.10 Partial adoption mixes damaged records with good ones and destroys the last known good state. Validate everything in a temporary value, then adopt all of it or none of it.

13.11 The same inputs and outputs make defects reproducible before randomness adds variation.

13.12 Normal: mixed catalogue returns one id, B2. Boundary: all issued returns an empty list, which is a correct answer.

Failure: a record missing the field is rejected by load validation, never silently counted. The shown run prints one id and count 1.

13.13 It is not a finite numeric measurement and can break ordinary comparison assumptions.

13.14 Input promises blank rejection; seat rules promise no double booking of one seat and slot; storage promises validated save and load. Build seat rules first, then input, then storage, replaying the checklist each time.

13.15 Install steps, the run command, sample input, the expected output and known limits. Beside them the report shows acceptance cases with actual versus expected results, one defect with its repair, and remaining limits.

13.16 Successful core flows, deliberate failure cases, persistence recovery and results matched against acceptance criteria.

13.17 Removing free B2 prints 1, the new count. Removing issued B1 prints “issued book kept” and the count stays 1.

Removing unknown B9 prints “unknown book”. Position search plus holder check plus unknown rejection cover the three behaviours.

13.18 The defect is a missing filter: issued books are counted as available. On one issued plus one free book it returns 2 ids instead of 1.

The repair keeps only records whose reader tag is empty. The regression check runs mixed, all-issued and all-free catalogues and expects 1, 0 and 2 ids.

End of book
You have reached the end