🐍 Python for Everyone

← Back to quiz

Chapter 33 Project — Final Chapter 75 min build

careerprep: a Mock-Interview Drill Tool + Portfolio Checklist Scanner

A real, multi-file, pip-installable command-line tool with two genuinely useful features for wrapping up this course: a mock-interview drill that saves your typed answers with a timestamp so you can watch them improve over multiple practice sessions, and a portfolio-readiness scanner that actually points at one of your own project folders and checks real files on disk — not a static list you tick by hand.

Project layout
project/
├── starter/            <- you work here
│   └── careerprep/
│       ├── __init__.py
│       ├── interview.py  (TODOs 1-10 -- question bank + answer storage)
│       ├── checklist.py  (TODOs 11-12 -- the directory scanner)
│       └── cli.py        (TODOs 11-25 -- the argparse wiring)
├── solution/            <- complete, working reference
│   ├── careerprep/
│   │   ├── __init__.py
│   │   ├── interview.py
│   │   ├── checklist.py
│   │   └── cli.py
│   ├── pyproject.toml
│   ├── requirements.txt
│   └── README.md

What you're building

Feature 1 — mock-interview drill (careerprep interview ...)
Feature 2 — portfolio checklist scanner (careerprep checklist ...)

A top-level --file <path> flag points interview commands at which JSON answers file to read/write (defaults to ~/.careerprep/answers.json). A top-level -v/--verbose flag raises the tool's own log level from INFO to DEBUG, scoped to careerprep's own logger only.

Why two modules, not one script interview.py and checklist.py hold the actual logic — reading/writing JSON, filtering questions, scanning a directory's real files. Neither imports argparse, touches sys.argv, or calls print(). cli.py holds the argparse parser, the input() calls that collect a typed answer, and is the only place that talks to the terminal. This is the same "separate the engine from the dashboard" split Chapter 31's taskbox project used.

Build it: interview.py

1 Filter and pick questions (TODOs 1-3)

get_questions validates the category and filters the built-in 25-question bank. pick_random_question reuses it and calls random.choice, raising CareerPrepError if a category has no matches (it never will, with this bank, but a learner adding new categories later would want that guard).

careerprep/interview.py (solution)
def pick_random_question(category: str | None = None) -> dict:
    """Pick one random question, optionally restricted to a category."""
    questions = get_questions(category)
    if not questions:
        raise CareerPrepError(f"No questions available for category {category!r}.")
    question = random.choice(questions)
    logger.debug("Picked random question #%d (category=%s)", question["id"], question["category"])
    return question

Thought process: the empty-result case has to be handled before calling random.choice, which raises a confusing IndexError on an empty sequence rather than a message that tells the caller what actually went wrong. Filtering first through the already-validated get_questions also means the category-validation logic lives in exactly one place, not duplicated here.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function pick_random_question(category: str | None = None) -> dict that picks one random question dict from a module-level QUESTION_BANK list (each item has "id", "category", "text" keys). It should reuse an existing get_questions(category) helper to get the filtered candidates, raise a custom CareerPrepError with a clear message if the filtered list is empty (don't let random.choice raise a raw IndexError on an empty sequence), and log a debug message with the picked question's id and category before returning it.

2 Load, save, and append answers (TODOs 4-9)

load_answers/save_answers mirror Chapter 31's load_tasks/save_tasks pattern exactly — missing file is a normal empty start, unreadable/corrupted file gets a clear wrapped error. The one detail that matters most here is record_answer: it must load the existing answers and append, never replace the file with just the new entry — losing past practice sessions defeats the entire point of a drill tool meant to show improvement over time.

careerprep/interview.py (solution)
def record_answer(answers_file: Path, question: dict, answer_text: str) -> dict:
    """
    Append a new answer to the answers file (never overwrite past ones --
    each practice session should add to the learner's history, not erase
    it, so they can see how their answers evolve over time).
    """
    answer_text = answer_text.strip()
    if not answer_text:
        raise CareerPrepError("Answer cannot be empty.")

    answers = load_answers(answers_file)
    entry = {
        "question_id": question["id"],
        "category": question["category"],
        "question_text": question["text"],
        "answer": answer_text,
        "answered_at": _now_iso(),
    }
    answers.append(entry)
    save_answers(answers_file, answers)
    logger.info("Saved answer for question #%d (%s)", question["id"], question["category"])
    return entry

Build it: checklist.py

3 Scan a real directory for objectively-checkable signals (TODOs 11-12)

scan_directory is the only function in this project that touches a real filesystem path a learner supplies. It checks four things a script genuinely can verify without judgment: does a README exist and clear a minimum length, does a dependency file exist, does a test file exist, does a .gitignore exist. Five more checklist items (README explains WHY, no hardcoded secrets, an honest limitations section, tests exercise real logic, meaningful commits) stay in manual_items() — a script that claimed to verify those would be lying about what it can actually see.

careerprep/checklist.py (solution)
def scan_directory(target: Path) -> dict[str, bool]:
    if not target.exists():
        raise CareerPrepError(f"No such directory: {target}")
    if not target.is_dir():
        raise CareerPrepError(f"Not a directory: {target}")

    logger.debug("Scanning %s for portfolio-readiness signals", target)

    readme = _find_file(target, README_FILENAMES)
    results = {
        "readme_substantial": readme is not None and _is_substantial(readme),
        "dependencies_declared": any((target / name).is_file() for name in DEPENDENCY_FILENAMES),
        "tests_exist": _has_tests(target),
        "gitignore_exists": (target / ".gitignore").is_file(),
    }
    logger.info("Scanned %s: %d/%d auto-checkable items passed", target, sum(results.values()), len(results))
    return results

Thought process: "does a README exist" and "is the README actually useful" are two very different questions — the first is a file-existence check, the second requires judgment a script can't make honestly. The temptation with an AI assistant is to let it collapse "exists" into "passes," which quietly overstates what the scanner actually verified (this is exactly the flaw planted in this chapter's AI-paired version — go compare after you've built this).

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function scan_directory(target: Path) -> dict[str, bool] that checks a real project directory for four portfolio-readiness signals: (1) "readme_substantial" -- a README.md (case-insensitive) exists AND its stripped text content is at least 200 characters long, not just present; (2) "dependencies_declared" -- a requirements.txt or pyproject.toml exists directly under target; (3) "tests_exist" -- either a tests/ folder containing at least one .py file, or a top-level/nested test_*.py or *_test.py file exists; (4) "gitignore_exists" -- a .gitignore file exists. Raise a custom CareerPrepError if target doesn't exist or isn't a directory. Use the logging module to log an info-level summary of how many of the 4 checks passed.

Build it: cli.py

4 Build the argparse parser with nested subcommands (TODOs 11-17)

This parser nests one level deeper than Chapter 31's taskbox: interview and checklist are each their own subparser with their own subparsers underneath (list/random/review, and list/scan). args.command tells you which top-level group ran; args.interview_command or args.checklist_command tells you which one inside that group.

careerprep/cli.py (solution)
subparsers = parser.add_subparsers(dest="command", required=True)

interview_parser = subparsers.add_parser("interview", help="mock-interview drill tool")
interview_sub = interview_parser.add_subparsers(dest="interview_command", required=True)

random_parser = interview_sub.add_parser("random", help="answer one random question")
random_parser.add_argument(
    "--category", choices=["behavioral", "technical"], default=None,
    help="only pick from this category",
)

checklist_parser = subparsers.add_parser("checklist", help="portfolio-readiness checklist")
checklist_sub = checklist_parser.add_subparsers(dest="checklist_command", required=True)

scan_parser = checklist_sub.add_parser("scan", help="scan a real directory and auto-check what's checkable")
scan_parser.add_argument("path", type=Path, help="path to the project directory to scan")

Thought process: two-level subcommands (careerprep interview random) need required=True on both levels of add_subparsers, not just the top one — forgetting it on the inner level means careerprep interview with no further argument silently does nothing instead of showing a clear "missing command" error.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write an argparse.ArgumentParser for a CLI tool called "careerprep" with two top-level subcommands via add_subparsers(dest="command", required=True): "interview" and "checklist". Each of those needs its OWN nested subparsers (also required=True): "interview" gets "list" (optional --category choices=[behavioral,technical]), "random" (same --category option), and "review" (--category AND optional --question-id type=int); "checklist" gets "list" (no arguments) and "scan" (one required positional "path" argument, type=Path). Also add top-level --file (type=Path) and -v/--verbose (store_true) flags before the subparsers. Return the built parser from build_parser() without calling parse_args().

5 Scoped logging, multi-line input, and error handling (TODOs 18-25)

configure_logging reuses Chapter 31's named-logger pattern (never logging.basicConfig()). read_multiline_answer is new for this chapter: it loops on input(), collecting lines until a blank one is entered, so a learner can write a real multi-paragraph STAR answer instead of one cramped line. main() wraps dispatch in try/except (InterviewError, ChecklistError) so a bad path or bad category becomes a clean one-line error, not a raw traceback.

terminal — a real error, not invented for the docs
$ careerprep checklist scan /tmp/does_not_exist_xyz
ERROR: No such directory: /tmp/does_not_exist_xyz
$ echo $?
1

A missing required subcommand never even reaches this code — argparse catches it, at whichever nesting level it happened, before main()'s body runs:

terminal
$ careerprep interview
usage: careerprep interview [-h] {list,random,review} ...
careerprep interview: error: the following arguments are required: interview_command
$ echo $?
2

Install it for real

terminal
cd chapters/chapter-33-interview-career-prep/project/solution
python3 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e .

Real output from actually running that install:

terminal
$ pip install -e .
Obtaining file:///.../chapter-33-interview-career-prep/project/solution
  Installing build dependencies: started
  Installing build dependencies: finished with status 'done'
  ...
Building wheels for collected packages: careerprep
  Building editable for careerprep (pyproject.toml): finished with status 'done'
  Created wheel for careerprep: filename=careerprep-1.0.0-0.editable-py3-none-any.whl ...
Successfully built careerprep
Installing collected packages: careerprep
Successfully installed careerprep-1.0.0

Feature 1, for real — mock-interview drill

terminal
$ careerprep --file /tmp/demo_answers.json interview random --category behavioral
============================================================
#2 [behavioral] Describe a time you disagreed with a teammate's code review feedback. How did you handle it?
============================================================
(Type or paste your answer. Press Enter on a blank line when you're done.)
Situation: our checkout API started 500ing under load.
Task: I needed to find root cause before the weekend traffic spike.
Action: I added structured logging around the payment call and traced it to a connection pool exhaustion bug.
Result: fixed the pool size and added an alert so we caught it early next time.

INFO: Saved answer for question #2 (behavioral)
Saved your answer for question #2 at 2026-07-12T05:42:02+00:00.

A second practice session on a different (random) question, then review showing both — proving the answers file appends, it never overwrites past sessions:

terminal
$ careerprep --file /tmp/demo_answers.json interview review
--- Answer 1 of 2 ---
[2026-07-12T05:42:02+00:00] #2 (behavioral) Describe a time you disagreed with a teammate's code review feedback. How did you handle it?
  Situation: our checkout API started 500ing under load.
  Task: I needed to find root cause before the weekend traffic spike.
  Action: I added structured logging around the payment call and traced it to a connection pool exhaustion bug.
  Result: fixed the pool size and added an alert so we caught it early next time.

--- Answer 2 of 2 ---
[2026-07-12T05:42:14+00:00] #17 (technical) What does `git rebase` do differently from `git merge`, and when would you reach for one over the other?
  A decorator wraps a function to add behavior without changing its source, e.g. logging execution time.
  Real use case: a @require_auth decorator on Flask view functions.

Feature 2, for real — checklist scan pointed at a real directory in this repo

This is careerprep checklist scan pointed at chapters/chapter-31-professional-python/project/solution/ — a real chapter folder in this repo. At the time of this scan, that folder has a 140-character README.md (below the 200-character "substantial" threshold), a pyproject.toml, no tests/ folder, and no .gitignore:

terminal
$ careerprep checklist scan ../../chapter-31-professional-python/project/solution
INFO: Scanned ../../chapter-31-professional-python/project/solution: 1/4 auto-checkable items passed
Scanning ../../chapter-31-professional-python/project/solution ...

Auto-checked (verified against real files on disk):
  [ ] README.md exists and is a non-trivial length (not a one-line placeholder)
  [x] requirements.txt or pyproject.toml declares dependencies
  [ ] At least one test file exists (tests/ folder or test_*.py / *_test.py)
  [ ] .gitignore exists

Manual self-assessment (not scannable -- be honest with yourself):
  [ ] README explains WHY the project exists, not just WHAT it does
  [ ] No hardcoded secrets or API keys anywhere in the codebase
  [ ] An honest 'Limitations' or 'Known Issues' section exists somewhere
  [ ] Tests actually exercise real logic, not just placeholder asserts
  [ ] Commit history shows incremental progress, not one giant commit

That result matches the real files on disk exactly. As a contrast, a folder that actually has all four (substantial README, requirements.txt, a real test file under tests/, and a .gitignore) reports a clean 4/4:

terminal
$ careerprep checklist scan /tmp/portfolio_demo
INFO: Scanned /tmp/portfolio_demo: 4/4 auto-checkable items passed
Scanning /tmp/portfolio_demo ...

Auto-checked (verified against real files on disk):
  [x] README.md exists and is a non-trivial length (not a one-line placeholder)
  [x] requirements.txt or pyproject.toml declares dependencies
  [x] At least one test file exists (tests/ folder or test_*.py / *_test.py)
  [x] .gitignore exists
Why requirements.txt is (correctly) empty careerprep only imports from the standard library: argparse, logging, json, pathlib, datetime, random, textwrap. There is nothing to pin. The file is kept — not deleted — with a comment explaining that.

Why this project matters

Every real interview loop combines exactly these two things: practicing how you talk about your work out loud, and having a portfolio that actually holds up when someone opens the folder. A checklist you never run against real files is just a list you feel good about; a mock-interview tool that doesn't save your answers gives you no way to notice you're getting better. This project is a small, honest version of both — the same shape you'd want for real job prep, built with the same subcommands-plus-package pattern you used for taskbox back in Chapter 31.

More project ideas

No starter/solution files are provided for these on purpose — building and verifying each one yourself is the point. Each is solvable with only what this chapter (and earlier chapters) have taught.

1 Add a --timer flag that times how long you take to answer each question

Scenario: Real interviews are timed, even if informally — a behavioral answer that takes eight minutes to get to the point is a real problem, and you won't notice unless you measure it.

What to do: Add a --timer flag to interview random. When set, start a timer (time.monotonic()) right after the question is printed, and stop it right after read_multiline_answer() returns. Print the elapsed time, and save it alongside the answer in the JSON entry (a new elapsed_seconds key).

Suggested approach: time.monotonic() before and after, subtract, round(..., 1) for a clean display — don't use time.time(), which can jump backward if the system clock adjusts mid-interview.

2 Add a 1-5 confidence self-rating after each answer

Scenario: Raw answer text doesn't tell you which questions you actually feel shaky on — a self-rating, tracked over time, does.

What to do: After saving an answer in interview random, prompt "How confident do you feel about that answer? (1-5): ", validate it's an int 1-5 (re-prompt on bad input), and save it in the JSON entry alongside the answer as a confidence key. Add a way to see your average confidence per question when reviewing.

Suggested approach: A small while True: input-validation loop, the same pattern you used in earlier chapters' menu-driven projects.

3 Extend the checklist scanner to check for a LICENSE file and a CI workflow

Scenario: Two more genuinely checkable portfolio signals: does the repo have an open-source license, and does it have any automated CI at all.

What to do: Add two more auto-checkable items to CHECKLIST_ITEMS: license_exists (a LICENSE, LICENSE.md, or LICENSE.txt file at the project root) and ci_workflow_exists (a .github/workflows/ folder containing at least one .yml/.yaml file). Wire both into scan_directory()'s results dict.

Suggested approach: Reuse the _find_file() helper pattern for LICENSE*; for the CI check, (target / ".github" / "workflows").is_dir() and any((target / ".github" / "workflows").glob("*.y*ml")).

4 Add an export-to-markdown feature that turns saved answers into a study guide

Scenario: A JSON file of past answers isn't something you'd actually review the night before an interview — a readable document is.

What to do: Add a new careerprep interview export <output.md> subcommand. It should load all saved answers (optionally filtered by --category), group them by question, and write a Markdown file with one ## Question text heading per question followed by each of your saved answers to it in chronological order.

Suggested approach: Build a dict[int, list[dict]] keyed by question_id from the loaded answers, then iterate it to build the Markdown string before writing it with Path(output).write_text(...).

← Quiz Now Pair With an AI →