MGU Computer Science Series — Programming with Python
Part VII: Capstone Programming Projects
Plan · Build · Test · Document · Present · Reflect
Chapter 30 of 30
30
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 30:
Building and Documenting
a Python Project

From requirements to a working, tested, and documented program — the complete cycle of real Python development

■ Part VII of VII ■

■ 11 Sections  •  Chapter 30 of 30  •  Capstone Chapter ■

Everything you have learned comes together here — the final chapter of Programming with Python

Chapter Introduction and Learning Objectives

This is the final chapter of Programming with Python. Everything you have learned — variables, conditionals, loops, functions, data structures, files, exceptions, classes, and code quality — comes together here. Your goal is to build one complete Python program from start to finish: planned, implemented, tested, improved, documented, and presented.

You have already written dozens of short programs. You have traced variable values, fixed bugs, designed functions, processed files, and organized classes. Now the question changes from can you write a program that does X to can you build a program worth using. That shift — from exercising a skill to building something real — is one of the most important transitions in a programmer's development.

The Capstone Question

A short program proves you understand a concept. A complete project proves you can combine many concepts into something that works as a whole, handles unexpected input, survives a restart, can be understood by someone else, and improves when you find its weaknesses. This chapter teaches you how to do all of that — systematically.

11Sections
8Objectives
12Key Terms
8Project Options

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Identify the qualities of a well-scoped beginner Python project.
  2. 2Write clear functional and non-functional requirements for a program.
  3. 3Design a central data structure and a function table before writing code.
  4. 4Use milestones and stub functions to build a program in stages while keeping it runnable at every step.
  5. 5Design and run deliberate test cases for individual functions and for the complete program.
  6. 6Refactor working code for clarity, consistency, and robustness.
  7. 7Write docstrings, inline comments, and a README that make a project understandable to others.
  8. 8Present a completed project by demonstrating its features, explaining its organization, and describing a problem that was solved during development.

Sections at a Glance

Sections 30.1 – 30.2
Choosing Well: What to Build and Why
Project Qualities · Scope · Selection · Common Mistakes

What Makes a Good Beginner Python Project

You have already written dozens of short programs. You have traced variable values, fixed bugs, designed functions, processed files, and organized classes. Now the question changes from can you write a program that does X to can you build a program worth using.

A good beginner Python project has five qualities.

Quality 1
It solves a real problem
The program should do something you could explain to someone who does not program. "It keeps track of books I want to read" is a clear purpose. "It tests my Python skills" is a learning goal, not a program purpose. A good project has both.
Quality 2
It is within reach
A first complete project should not require machine learning, web frameworks, graphical interfaces, or external APIs. It should run in the terminal, use files or standard input for data, and rely entirely on what you have learned. Simplicity is not weakness.
Quality 3
It combines multiple skills
A good capstone uses at least functions, one or more data structures, file input or output, exception handling, and conditional logic. It should not be a single loop with a counter. It should have moving parts that work together.
Quality 4
It can grow
A good project starts with a working core and leaves room for optional improvements. You should be able to release version one and then improve it. Programs that try to do everything at once rarely finish.
Quality 5
It can be explained
You should be able to describe what your program does, how it is organized, what the main functions do, and what data it stores. If you cannot explain your program, the design needs work — not you.
A Focused, Working Program Wins

A focused, working, readable program is far more impressive than an ambitious, broken, incomprehensible one. Scope down aggressively on a first capstone project. You can always extend it after it works.

Choosing a Project

Section 30.10 lists several project options at different levels. Before choosing, ask yourself three questions.

What problem do I actually care about? The best projects come from genuine frustration or genuine curiosity. If you actually want a program to track your reading list, you will be more motivated to finish it than if you picked a project randomly.

How much time do I have? A realistic project for two to three weeks of focused work is very different from a one-weekend sprint. Section 30.4 discusses milestones. Estimate how many working sessions you have, then choose a scope that fits.

Do I understand what the program needs to do before I start writing code? If you cannot describe the program's purpose, inputs, outputs, and data storage in plain language, you are not ready to write a line of Python yet. Take time to think before you open your editor.

Common Beginner Project Mistakes

Choosing a project that depends on external packages you do not know yet. Trying to build a mobile app, website, or graphical application. Designing a project with no data storage — programs that only print menus and do arithmetic are not real applications. Starting to code before you have a clear description of what the program does.

Sections 30.3 – 30.5
Designing Before Coding: Requirements, Milestones, and Data
Requirements · Milestones · Data Design · Program Flow · Function Table

Writing Requirements

Requirements are plain-language descriptions of what your program must do. They come before code. Writing them down forces you to think clearly and gives you a checklist to test against.

There are two levels of requirements useful for a beginner project.

Functional requirements describe what the program does. They answer: what can the user do with this program?

Non-functional requirements describe how the program behaves. They answer: how does the program handle bad input? what happens when the file is missing? should the program be fast, simple, or readable?

Worked Example — Personal Study Tracker Requirements
The Study Tracker helps a student log study sessions, track time per subject, and review progress
  • FR 1Log a study session by entering a subject name, the number of minutes studied, and an optional note.
  • FR 2View a summary of total minutes studied per subject.
  • FR 3View all sessions for a specific subject.
  • FR 4View the most recent sessions across all subjects.
  • FR 5Save sessions to a file and load them when the program starts.
  • FR 6Exit the program cleanly.
  • NFR 1All input validation catches bad data (negative minutes, empty subject names) and prompts the user again.
  • NFR 2File loading handles a missing file gracefully on first run.
  • NFR 3The program uses clear menus with numbered options and does not crash on unexpected input.
How to Write Requirements

Write requirements as numbered statements. Use plain language. Write what the program must do, not how it does it — you will figure out how during planning and implementation. After writing your requirements, read them aloud. Ask: if someone built exactly what is written here, would it be useful?

Planning Milestones

A milestone is a point in development where your program can do something real and testable. Milestones work against a common beginner trap: trying to build everything at once and having nothing working for weeks. If you hit a wall, you want to be able to step back to the last working version, not rebuild from zero.

A good beginner project has three to five milestones.

Milestone Pattern
A reliable five-milestone structure for most beginner projects
  • Milestone 1Core data structure and basic function. Before menus, files, or anything fancy, get the fundamental data moving. Prove the core idea works.
  • Milestone 2Working menu loop. Add a menu that lets the user choose actions. The actions do not all have to work yet, but the loop should run and exit cleanly.
  • Milestone 3All core features working without files. The program should be fully functional in memory. All menu options work, input validation works, summaries display correctly.
  • Milestone 4File saving and loading. Persist data between sessions. Test that saving then reloading gives back exactly the same program state.
  • Milestone 5Polish and documentation. Add docstrings, improve output formatting, handle edge cases, remove dead code, and write the README.

Worked Example: Study Tracker Milestone Table

MilestoneGoalDone When
1Data structure for a session, add_session() functionOne session can be created and printed
2Menu loop with all options listedUser can navigate menu; program exits cleanly
3All features working in memoryLog, view summary, view subject, view recent all work
4File saving and loadingSessions survive program restart
5PolishClean output, docstrings, edge cases handled
Write This Before You Code

Write your own milestone table before writing a single line of code. It is a five-minute investment that will save hours of confusion later.

Designing Data and Program Flow

Good programs are designed twice: once in words, once in code. The design in words is faster, cheaper to change, and easier to share. Never skip it.

Designing Your Data

Ask: what information does this program need to store? For the Study Tracker, each session needs a subject name, a number of minutes, an optional note, and the date it was logged. A single session is a dictionary:

Python — Session Dictionary
# A single session as a dictionary
session = {
    "subject": "Mathematics",
    "minutes": 45,
    "note": "Practiced integration by parts",
    "date": "2025-09-14"
}

# All sessions together are a list of these dictionaries
sessions = [
    {"subject": "Mathematics", "minutes": 45, "note": "...", "date": "2025-09-14"},
    {"subject": "Python",      "minutes": 60, "note": "...", "date": "2025-09-14"},
    {"subject": "Mathematics", "minutes": 30, "note": "...", "date": "2025-09-15"}
]

This is the central data structure. Sketch it in plain language and then as Python before writing any other code.

Designing Your Program Flow

Study Tracker — Main Loop in Plain Language
Write this before writing the menu function
  • Step 1Load sessions from file, or start with an empty list if file does not exist.
  • Step 2Show menu.
  • Step 3Get user choice.
  • Steps 4–8Dispatch to the appropriate function based on the choice: log session, show summary, show subject, show recent, or save and exit.
  • Step 9If choice is invalid: show error and repeat menu.
  • Step 10After any action, return to Step 2.

Designing Your Functions

List every function you expect to write. Give each one a name, its parameters, what it returns or does, and one sentence describing its job.

FunctionParametersReturnsJob
add_sessionsessions, subject, minutes, noteUpdated sessions listCreates and appends a session dictionary
show_summarysessionsNothing (prints)Prints total minutes per subject
show_subject_sessionssessions, subjectNothing (prints)Prints all sessions for one subject
show_recent_sessionssessions, nNothing (prints)Prints the last n sessions
save_sessionssessions, filenameNothingSaves sessions to a CSV file
load_sessionsfilenamesessions listLoads sessions from CSV, returns list
get_valid_minutesNoneIntegerPrompts user until a valid positive integer is entered
run_menusessionsNothingDisplays menu, handles user choices
The Rule: Design Before You Type

This function table is your implementation plan. Build one function at a time. Test each one before moving to the next. When you are building from a plan, you always know what you are doing next. Without a plan, you invent the structure as you go — and invented structure is usually confused structure.

Sections 30.6 – 30.8
Building, Testing, and Improving
First Version · Stubs · Testing · Regression · Refactoring

Building the First Working Version

The first working version does one thing: it proves the core idea works. It does not need to be polished, complete, or well-documented. It needs to be real, runnable code you can build on.

Start With the Data Structure

Python — add_session and quick test
def add_session(sessions, subject, minutes, note=""):
    """Add a new study session to the sessions list."""
    from datetime import date
    session = {
        "subject": subject,
        "minutes": minutes,
        "note": note,
        "date": str(date.today())
    }
    sessions.append(session)
    return sessions


# Quick test — run this before adding anything else
sessions = []
sessions = add_session(sessions, "Mathematics", 45, "Integration practice")
sessions = add_session(sessions, "Python", 60, "Working on capstone")
print(sessions)
Run First, Extend Second

Run this and make sure it works before continuing. Every new function should be tested in isolation before being connected to the menu loop.

Stub Functions

A stub function has the right name and parameters but does not do anything real yet. It lets you run and test the menu before every feature is finished. Replace stubs one at a time.

Python — Stub Functions
def get_valid_minutes():
    """Prompt user until a valid positive integer is entered."""
    return 30  # Stub: always returns 30 for now


def show_subject_sessions(sessions, subject):
    """Print all sessions for a given subject."""
    print("(Not yet implemented)\n")  # Stub


def show_recent_sessions(sessions, n=5):
    """Print the most recent n sessions."""
    print("(Not yet implemented)\n")  # Stub


def save_sessions(sessions, filename):
    """Save sessions to a CSV file."""
    print(f"(Stub: would save {len(sessions)} sessions to {filename})\n")


def load_sessions(filename):
    """Load sessions from a CSV file."""
    return []  # Stub: always returns empty list

The Main Block

Python — Entry Point
if __name__ == "__main__":
    sessions = load_sessions("study_sessions.csv")
    run_menu(sessions)
Always Use if __name__ == "__main__":

Protecting your main code with this guard is good Python practice. It ensures that importing your file in a test or another module does not accidentally run the program. Every Python script that is meant to be run directly should have it.

Testing and Debugging the Project

Testing a full program is different from testing a single function. You need to test individual pieces and also how they work together.

Test Each Function Alone First

Python — Function-Level Testing
# Test add_session
sessions = []
sessions = add_session(sessions, "History", 30, "Read chapter 4")
assert len(sessions) == 1
assert sessions[0]["subject"] == "History"
assert sessions[0]["minutes"] == 30
print("add_session: PASSED")

# Test show_summary with known data
sessions = []
sessions = add_session(sessions, "History", 30)
sessions = add_session(sessions, "History", 45)
sessions = add_session(sessions, "Python", 60)
# Expected: History = 75 minutes, Python = 60 minutes
show_summary(sessions)
# Read the output and verify manually

Design Test Cases With Intention

Test Case — get_valid_minutesInputExpected Behavior
Normal case"45"Returns 45
Zero"0"Re-prompts (zero is not a valid session length)
Negative"-10"Re-prompts (negative is invalid)
Non-numeric"abc"Re-prompts (not a number)
Empty string""Re-prompts (empty input)
Large valid value"120"Returns 120

Testing File Saving and Loading

Test these scenarios explicitly, not casually.

File Testing Checklist
Run each scenario by hand and verify the result
  • Scenario 1Run the program with no save file present. Does it start cleanly without crashing?
  • Scenario 2Log several sessions, save, and exit. Restart the program. Do the sessions reappear?
  • Scenario 3Log one session, save. Log more sessions, save again. Are all sessions present when reloaded?
  • Scenario 4Manually delete the save file. Does the program start cleanly on next launch?
Regression Testing

Every time you add a feature or fix a bug, re-run your earlier tests. A fix in one place sometimes breaks something that worked before. This is called a regression. Testing old behavior after new changes is called regression testing. It takes a few minutes and saves a lot of pain.

Improving and Refactoring

Once all your core features work and pass testing, improve the program. Improvement happens in two directions: completing stubs with real implementations, and refactoring existing code to be cleaner.

Complete: get_valid_minutes

Python — Input Validation Loop
def get_valid_minutes():
    """Prompt the user until a valid positive integer is entered.

    Returns:
        int: A positive number of minutes.
    """
    while True:
        raw = input("Minutes studied: ").strip()
        try:
            minutes = int(raw)
            if minutes <= 0:
                print("Please enter a positive number of minutes.")
                continue
            return minutes
        except ValueError:
            print("Please enter a whole number.")

Complete: save_sessions and load_sessions

Python — CSV File Persistence
import csv


def save_sessions(sessions, filename):
    """Save all sessions to a CSV file.

    Args:
        sessions (list): The list of session dictionaries to save.
        filename (str): Path to the output CSV file.
    """
    fieldnames = ["subject", "minutes", "note", "date"]
    try:
        with open(filename, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(sessions)
    except OSError as e:
        print(f"Error saving sessions: {e}")


def load_sessions(filename):
    """Load sessions from a CSV file.

    Args:
        filename (str): Path to the CSV file to load.

    Returns:
        list: A list of session dictionaries, or an empty list if file not found.
    """
    sessions = []
    try:
        with open(filename, newline="", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                row["minutes"] = int(row["minutes"])  # CSV stores strings
                sessions.append(row)
    except FileNotFoundError:
        pass  # Normal on first run
    except OSError as e:
        print(f"Error loading sessions: {e}")
    return sessions

Refactoring Opportunities to Look For

Refactoring TargetWhat to Do
Remove duplicationIf two functions do something very similar, extract a shared helper
Improve output formattingAlign columns; use consistent spacing; add blank lines between sections
Simplify complex conditionsExtract a hard-to-read if statement into a Boolean variable with a clear name
Improve variable namesRename s to session, m to minutes — unless the short form is genuinely clearer in context
Improve error messagesEvery error message should tell the user what went wrong and what to do
Avoid Premature Optimization

There is a trap called premature optimization: spending time improving things that are not problems. At the beginner stage, rewriting working code in a cleverer way with no benefit, adding features not in your requirements, and redesigning a data structure that already works are all ways to not finish. Finish the program you planned. Then improve it.

Sections 30.9 – 30.11
Finishing Well: Documentation, Presentation, and Reflection
Docstrings · README · Presenting Code · Growth as a Programmer

Writing Documentation

Documentation explains your program to someone who did not write it — and to yourself six months from now. A complete beginner project has three levels of documentation.

Level 1: Docstrings

Every function should have a docstring. A docstring is a string literal immediately after the def line. It explains what the function does, what its parameters mean, and what it returns.

Python — Docstring Example
def add_session(sessions, subject, minutes, note=""):
    """Add a new study session to the sessions list.

    Args:
        sessions (list): The existing list of session dictionaries.
        subject (str): The name of the subject studied.
        minutes (int): The number of minutes spent studying.
        note (str): An optional note about the session. Defaults to "".

    Returns:
        list: The sessions list with the new session appended.
    """
    from datetime import date
    session = {
        "subject": subject,
        "minutes": minutes,
        "note": note,
        "date": str(date.today())
    }
    sessions.append(session)
    return sessions

Level 2: Inline Comments

Use inline comments for anything not obvious from the code itself. Do not comment obvious things.

Python — Good vs. Unhelpful Comments
# Good: explains why, not what
recent.reverse()  # Most recent sessions should appear first
row["minutes"] = int(row["minutes"])  # CSV stores all values as strings

# Bad: restates the code with no added meaning
count += 1  # Add 1 to count

Level 3: README File

Every project should have a README.md file in the same folder as the program. A good README has a one-sentence description, how to run the program, how to use it, what files are included, known limitations, and author and date.

Sample README — Personal Study Tracker
This text goes in a file named README.md in your project folder
  • TitlePersonal Study Tracker — A command-line Python program for logging and reviewing study sessions.
  • What It DoesLog study sessions with subject, time, and optional notes. View total time per subject. Browse sessions by subject or date. Save data between sessions in a CSV file.
  • How to RunMake sure Python 3 is installed. Run: python study_tracker.py. No additional packages required.
  • Filesstudy_tracker.py — Main program. study_sessions.csv — Auto-generated data file (created on first save).
  • LimitationsSessions cannot be deleted or edited after logging. No support for time-based sorting. No export to formats other than CSV.
Documentation Forces Clarity

Writing docstrings and a README also forces you to articulate what your functions actually do. Sometimes you discover you cannot explain a function clearly — which means the function itself is unclear. Documentation is not just for readers; it improves the code it describes.

Presenting the Project

Whether you present in class or submit for grading, you should be ready to walk someone through your program and explain your decisions. A good project presentation covers five areas.

Area 1
What the program does
Run the program and demonstrate its main features. Show a real use case from start to finish: launch, enter a few sessions, view a summary, save, exit, relaunch, and see the saved data reappear.
Area 2
How the program is organized
Open the source file and give a quick map: here is the data structure, here are the main functions, here is the menu loop, here is where saving and loading happen.
Area 3
One function you are proud of
Choose the most interesting or carefully designed function. Explain what it does, show the code, and walk through a concrete example.
Area 4
One problem you solved
Describe a real bug or design problem you encountered, how you diagnosed it, and how you fixed it. This is often more impressive than the working code itself.
Area 5
What you would improve next
A good programmer always knows the next step. Describing your next improvement shows that you understand your program's current limits — and that you have a plan.

Tips for Presenting Code

Use a font large enough to read from a distance. Highlight the section you are discussing. Read key lines aloud: "This line opens the file for reading." Explain why you made design choices, not just what the code does.

Reflecting on Growth as a Programmer

Take time to look back at your first programs from Chapter 3 and Chapter 4. Compare them to what you have just built. The difference is not only in size or complexity. It is in how you think.

At the beginning of this course, programming probably felt like solving a puzzle by guessing. Now it should feel more like engineering: designing, planning, building in stages, testing deliberately, reading your own code with critical eyes, and improving it systematically.

The Habits You Have Built

HabitWhat It Means Now
You read code before you write itYou can trace variable values, predict output, and spot bugs in code you did not write. This is one of the most valuable programming skills there is.
You design before you typeYou know how to write requirements, sketch a data structure, list your functions, and plan program flow on paper before opening your editor.
You test with intentionYou know the difference between testing casually and designing test cases. You know what edge cases are and why they matter.
You debug systematicallyYou read error messages instead of panicking. You use print-style debugging. You change one thing at a time.
You organize code to communicateYour functions have names that explain what they do. Your docstrings tell the next programmer — and future you — what each piece does.

These habits matter more than any particular piece of syntax. Python itself will change. New versions will add features. Libraries will come and go. The habits of a careful, methodical programmer transfer across every language, tool, and project.

What Comes Next

Next Path A
Data Structures and Algorithms
Measure program efficiency, work with trees and graphs, sort and search large datasets, and solve more complex computational problems.
Next Path B
Python for Data Science
Learn NumPy, pandas, matplotlib, and Jupyter notebooks. Apply programming to real datasets.
Next Path C
Python for Web Development
Learn Flask or Django. Build programs that run in a browser and respond to web requests.
Next Path D
Python for Automation
Learn pathlib, os, shutil, and scripting tools that automate real file and system tasks.
Next Path E
Game Programming with Python
Learn Pygame and apply your programming knowledge to interactive games with graphics and real-time input.
Next Path F
Open Source Contribution
Find a Python project you use, read its source code, and try contributing a small fix. Reading real production code is one of the fastest ways to grow.
A Final Thought

Programming is not memorizing syntax. It is the disciplined practice of expressing ideas as precise instructions, testing those instructions against reality, and improving them until they work. You have been practicing that discipline throughout this book.

Keep building.

Chapter Summary

Key Terms

requirements
Plain-language descriptions of what a program must do, written before coding begins.
functional requirements
Requirements describing what the user can do with the program — the actions and features the program must support.
non-functional requirements
Requirements describing how the program behaves — how it handles bad input, missing files, or other conditions not part of normal use.
milestone
A defined point in development where the program can do something real and testable — an anchor in the development process.
stub function
A function with the correct name and parameters but no real implementation yet, used to keep the program runnable while other parts are being built.
regression
A bug introduced by a change that breaks something that previously worked correctly.
regression testing
Re-running earlier tests after making changes, to confirm that existing behavior is preserved.
docstring
A string literal placed immediately after a def statement to document a function's purpose, parameters, and return value.
README
A plain-language project description file, typically named README.md, explaining what a program does and how to use it.
refactoring
Improving the structure and readability of existing code without changing what it does.
premature optimization
Spending time improving code performance or structure before the program works correctly, at the cost of finishing the actual program.
program flow
The sequence of steps a program follows from start to finish — designed in plain language before being expressed in code.
TemplateProject Planning Template

Use this template before you write a single line of Python. Fill it in on paper or in a text file.

Project Planning Template
Project Title:

One-sentence description:

Functional Requirements:
1.
2.
3.
4.
5.

Non-Functional Requirements:
1.
2.
3.

Central Data Structure (plain language, then sketch as Python):


Function List:
| Function Name | Parameters | Returns | Job |
|---------------|------------|---------|-----|
|               |            |         |     |

Program Flow (numbered steps):
1.
2.
3.
...

Milestone Plan:
| Milestone | Goal | Done When |
|-----------|------|-----------|
| 1         |      |           |
| 2         |      |           |
| 3         |      |           |
| 4         |      |           |
| 5         |      |           |
ProjectsCapstone Project Options

Choose one project appropriate to your available time and interest. Build the core scope first — extend only after it works.

Project A — Worked Example in This Chapter
Personal Study Tracker
Core Scope
Log study sessions with subject, minutes, and a note. View a summary by subject. View recent sessions. Save and load from a CSV file.
Extended Scope
Add goal-setting per subject. Show progress toward each goal in the summary. Warn when a subject has fallen below its weekly target.
Project B
Budget Tracker
Core Scope
Log income and expense entries with amount, category, and description. View a summary of spending by category. View total balance. Save and load from a file.
Extended Scope
Set a spending limit per category. Warn the user when a category exceeds its limit. Show monthly totals when entries include dates.
Project C
Vocabulary Flashcard Program
Core Scope
Store a vocabulary list with words and definitions. Quiz the user by showing a word and asking for the definition. Track how many were correct. Allow adding new words. Save and load from a file.
Extended Scope
Track a difficulty score per word. Show harder words more often during quizzes. Show the user their weakest words at the end of each session.
Project D
To-Do List Manager
Core Scope
Add, view, and mark tasks as complete. Show all incomplete tasks. Show all completed tasks. Save and load from a file.
Extended Scope
Assign a priority level (high, medium, low) to each task. Sort the task list by priority. Add due dates and warn about overdue tasks.
Project E
Grade Calculator
Core Scope
Enter assignments with name, score, and maximum points. Calculate and display the current course grade as a percentage. View a list of assignments sorted by score. Save and load from a file.
Extended Scope
Support multiple courses. Assign weights to categories (homework, exams, projects). Show what score is needed on remaining assignments to reach a target grade.
Project F
Contact Book
Core Scope
Add contacts with name, phone number, and email. Search by name. View all contacts alphabetically. Save and load from a file.
Extended Scope
Add a notes field per contact. Search by any field, not just name. Export the contact list as a formatted plain-text file.
Project G
Simple Text-Based Quiz Game
Core Scope
Load quiz questions from a CSV file with question, four choices, and correct answer. Present questions one at a time. Track the score. Show the final score at the end.
Extended Scope
Track which questions the user got wrong. Offer a second-chance review round with only incorrect questions. Save the high score across sessions.
Project H
File Organizer Planner
Core Scope
Read a folder's file listing from a text file (one filename per line). Categorize files by extension. Count how many files fall into each category. Generate a plain-text report.
Extended Scope
Detect duplicate filenames. Generate a suggested organization plan showing which files would move to which folder. Write the plan to an output file for review before any actual file moves.
Testing Checklist
Use before submitting or presenting your project
Function-Level Tests
  • Each function has been tested with normal inputs
  • Each function has been tested with edge case inputs
  • Each function that validates input has been tested with invalid inputs
  • Functions that return values have been tested by checking the return value, not just printing it
Program-Level Tests
  • The full menu loop runs without crashing
  • Every menu option works
  • Invalid menu choices are handled gracefully
  • The program exits cleanly
File Tests
  • Saving creates the file
  • Loading after saving restores all data correctly
  • The program starts cleanly when the save file does not exist
  • The program handles a corrupted or empty save file without crashing
Input Validation Tests
  • Empty input is handled
  • Wrong data types (letters where a number is expected) are handled
  • Numbers out of valid range are handled
  • Very long strings are handled
Documentation Checklist
Verify before submission
Code Quality
  • Every function has a docstring with description, parameters, and return value
  • Inline comments explain non-obvious logic (not obvious statements)
  • No dead code — no commented-out blocks, unused functions, or leftover debugging prints
  • Variable and function names are readable and descriptive
  • The file has a header comment with title, author, date, and brief description
Project Files
  • A README file is included in the project folder
  • The README includes title, description, how to run, files list, and known limitations
  • All required features are working and tested
  • Name and date appear in the file header
Presentation Checklist
Be ready to cover these five areas
Demonstration
  • I can demonstrate the program from launch to exit
  • I can show data being saved and reloaded across a program restart
Explanation
  • I can describe the central data structure in plain language
  • I can explain what each major function does
  • I can trace through one function call with a concrete example
Reflection
  • I can describe one bug I found and how I fixed it
  • I can describe what I would improve if I had more time
ReviewCumulative Python Review

These questions draw on skills from across the entire textbook. Suitable for final exam preparation, independent review, or instructor-assigned exercises.

Vocabulary Review

  1. What is the difference between a syntax error and a logic error?
  2. What does a function's return value mean? How is it different from printing?
  3. What is scope? Why do local variables not exist outside their function?
  4. What is the difference between a list and a dictionary?
  5. What does the with statement do when opening a file?
  6. What is an exception? What does try and except do?
  7. What is a class? What is an instance?
  8. What does it mean to refactor code?
  9. What is a docstring? Why should every function have one?
  10. What is a milestone in project development?

Code Reading

Read each program carefully and answer the question below it.

Code Reading — Question 1
data = [12, 7, 19, 3, 15]
result = 0
for value in data:
    if value > 10:
        result += value
print(result)

What does this program print? What would you rename result to better describe what it holds?

Code Reading — Question 2
def mystery(text):
    count = 0
    for char in text:
        if char in "aeiouAEIOU":
            count += 1
    return count

print(mystery("Programming"))
print(mystery("Python"))

What does mystery do? What is a better name for it? What does it print?

Code Reading — Question 3
records = [
    {"name": "Alice", "score": 88},
    {"name": "Bob",   "score": 74},
    {"name": "Carol", "score": 95}
]

for record in records:
    if record["score"] >= 90:
        print(record["name"], "passed with distinction")
    elif record["score"] >= 75:
        print(record["name"], "passed")
    else:
        print(record["name"], "did not pass")

What does this program print? What would happen if the list were empty?

Code Reading — Question 4
def load_data(filename):
    items = []
    try:
        with open(filename) as f:
            for line in f:
                items.append(line.strip())
    except FileNotFoundError:
        pass
    return items

What does this function return if the file exists? What does it return if the file does not exist? Why is pass used in the except block?

Debugging Practice

Each code sample contains at least one error. Identify the error and write a corrected version.

Bug 1
def total(numbers)
    result = 0
    for n in numbers:
        result += n
    return result
Bug 2
scores = [85, 90, 78, 92]
average = sum(scores) / len(scores)
print("Average: " + average)
Bug 3
result = is_passing(75)
if result = True:
    print("Passing")
Bug 4
counts = {}
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
for word in words:
    counts[word] = counts[word] + 1
print(counts)

Short Programming Tasks

  1. Write a function clean_name(name) that takes a string, strips whitespace from both ends, and returns the name with the first letter of each word capitalized.
  2. Write a function find_above_average(numbers) that takes a list of numbers and returns a new list containing only the values above the average. If the list is empty, return an empty list.
  3. Write a function count_by_category(items) that takes a list of dictionaries, each with a "category" key, and returns a dictionary mapping each category to the number of items in it.
  4. Write a function safe_divide(a, b) that returns the result of a / b but returns None if b is zero. Write three test calls demonstrating normal use, zero division, and using the result in a print statement.
  5. Write a function load_words(filename) that reads a text file where each line is one word, and returns a list of those words with whitespace stripped. If the file is not found, print a message and return an empty list.
ReflectionFinal Reflection

Write answers to these questions in your notebook or study journal before moving on.

  1. What was the hardest concept in this course for you? What helped you understand it?
  2. Describe a program you wrote that did not work the first time. How did you figure out what was wrong?
  3. What is the most useful Python skill you learned? Why?
  4. What do you wish you had understood earlier in the course that would have helped you?
  5. What kind of programs do you want to build next? What skills would you need to learn to build them?
  6. Compare how you thought about programming at the beginning of the course to how you think about it now. What has changed?

Course Completion Review

You have completed Programming with Python. Here is every major skill developed across all seven parts.

PartMajor Skills
Part IRunning Python, values and variables, expressions, arithmetic, input and output, simple programs, comments
Part IIBooleans, comparisons, conditionals, while loops, for loops, code tracing, debugging, test cases
Part IIIDefining and calling functions, parameters, return values, scope, decomposition, modules, standard library
Part IVStrings, lists, tuples, sets, dictionaries, nested data structures, choosing the right structure
Part VText files, CSV files, exceptions, dates, randomness, simulation, automation scripts
Part VIClasses, object state, methods, application design, testing, refactoring, code quality
Part VIIProject planning, requirements, milestones, data design, implementation, testing, documentation, presentation
MGU Library Connection
  • Programming with Python — Appendix M: Capstone Project Guide
  • Programming with Python — Appendix L: Testing and Refactoring Reference
  • Programming with Python — Appendix F: Code Style Guide
  • Programming with Python — Appendix N: Full Glossary of Python Terms
  • Companion resource: Python Project Checklist
  • Companion resource: Capstone Project Rubric
  • Next course: Data Structures and Algorithms (requires this course as prerequisite)
  • Next course: Python for Data Science (alternative pathway)
End of Programming with Python
You Are Ready for the Next Course

This textbook brought you from running your first Python script to building a complete, documented, tested program. You have learned to read code, design before coding, test deliberately, debug systematically, and write clearly. Those habits belong to you now — carry them into everything you build next.