Project Workshop — CLI Grade Calculator
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
Python · argparse · f-strings
Expected effort: 5–8 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | int/float/str/bool/None produces the specified behavior inside Variables & data types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | type conversion: int()/str()/float() produces the specified behavior inside Variables & data types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | id() and is vs == produces the specified behavior inside Variables & data types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | constants convention produces the specified behavior inside Variables & data types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | if/elif/else + nested conditions produces the specified behavior inside Control flow | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | for: range()/enumerate()/zip() produces the specified behavior inside Control flow | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | while + break/continue/else produces the specified behavior inside Control flow | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | ternary expressions produces the specified behavior inside Control flow | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.5 | match/case (Python 3.10+) produces the specified behavior inside Control flow | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | def/return/default args/args/kwargs produces the specified behavior inside Functions & scope* | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | LEGB scope rule produces the specified behavior inside Functions & scope | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | lambda functions produces the specified behavior inside Functions & scope | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | closures produces the specified behavior inside Functions & scope | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | list comp vs for loop produces the specified behavior inside Comprehensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | dict comp + filtering produces the specified behavior inside Comprehensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | set comp for deduplication produces the specified behavior inside Comprehensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | nested comprehensions produces the specified behavior inside Comprehensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | f-strings + format specifiers produces the specified behavior inside String formatting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | format() method produces the specified behavior inside String formatting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | Template strings produces the specified behavior inside String formatting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | strip/split/join/replace/find produces the specified behavior inside String formatting | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | case conversion: lower/upper/casefold/title/capitalize/swapcase produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | prefix and suffix: startswith/endswith/removeprefix/removesuffix produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | search and count: index/rindex/rfind/count produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | partitioning: partition/rpartition/splitlines produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.5 | character tests: isalpha/isdigit/isdecimal/isnumeric/isalnum/isspace/isidentifier produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.6 | translation and encoding: maketrans/translate/encode produces the specified behavior inside Complete string method reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── src/3│ ├── __init__.py4│ ├── cli.py5│ ├── models.py6│ ├── services.py7│ ├── repository.py8│ └── errors.py9├── tests/{test_cli.py,test_services.py,test_repository.py}10├── pyproject.toml11├── README.md12└── .gitignoreBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Variables & data types | int/float/str/bool/None; type conversion: int()/str()/float(); id() and is vs == | Demonstration plus focused tests |
| 2 | Control flow | if/elif/else + nested conditions; for: range()/enumerate()/zip(); while + break/continue/else | Demonstration plus focused tests |
| 3 | Functions & scope | def/return/default args/args/*kwargs; LEGB scope rule; lambda functions | Demonstration plus focused tests |
| 4 | Comprehensions | list comp vs for loop; dict comp + filtering; set comp for deduplication | Demonstration plus focused tests |
| 5 | String formatting | f-strings + format specifiers; format() method; Template strings | Demonstration plus focused tests |
| 6 | Complete string method reference | case conversion: lower/upper/casefold/title/capitalize/swapcase; prefix and suffix: startswith/endswith/removeprefix/removesuffix; search and count: index/rindex/rfind/count | Demonstration plus focused tests |
| 7 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1from collections.abc import Iterable2
3def report(name: str, scores: Iterable[float]) -> str:4 clean = [float(score) for score in scores]5 if not clean:6 raise ValueError("at least one score is required")7 if any(not 0 <= score <= 100 for score in clean):8 raise ValueError("scores must be between 0 and 100")9 average = sum(clean) / len(clean)10 grade = "A" if average >= 90 else "B" if average >= 75 else "C" if average >= 60 else "D"11 return f"{name.strip().title():<18} {average:6.2f} {grade}"12
13print(report(" dev gupta ", [81, 94, 88]))Expected result
1Dev Gupta 87.67 BCode reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from collections.abc import Iterable | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | def report(name: str, scores: Iterable[float]) -> str: | Defines a function; its parameters form the explicit input boundary. |
| 4 | clean = [float(score) for score in scores] | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | if not clean: | Evaluates the condition and enters this branch only when it is truthy. |
| 6 | raise ValueError("at least one score is required") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 7 | if any(not 0 <= score <= 100 for score in clean): | Evaluates the condition and enters this branch only when it is truthy. |
| 8 | raise ValueError("scores must be between 0 and 100") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 9 | average = sum(clean) / len(clean) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | grade = "A" if average >= 90 else "B" if average >= 75 else "C" if average >= 60 else "D" | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 11 | return f"{name.strip().title():<18} {average:6.2f} {grade}" | Returns the observable result to the caller and ends this invocation. |
| 13 | print(report(" dev gupta ", [81, 94, 88])) | Emits the example's observable output. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Variables & data types | An uppercase name pointing to a mutable list can still be mutated; convention is not immutability. | Use constants for stable configuration-independent values and enums for a closed domain vocabulary. |
| Control flow | Writing case STATUS_OK: usually captures anything unless it is a qualified constant; use enums or qualified names. | Use it for tagged records, protocol messages, and algebraic-style variants where structure is clearer than repeated indexing. |
| Functions & scope | Late binding in loops captures the variable, not its historical value; bind a default argument when needed. | Use closures for configured callbacks and small stateful factories. |
| Comprehensions | Reversing clause order changes both binding availability and output order. | Use at most a small, readable nesting and spell out loops when indexes or conditions are nontrivial. |
| String formatting | strip('.txt') removes any of those characters from both ends; use removesuffix('.txt') for an exact suffix. | Normalize at boundaries and prefer separator join over repeated concatenation in a loop. |
| Complete string method reference | Ignoring decode errors can silently lose or alter data, while repeatedly encoding/decoding adds work and ambiguity. | Keep text as str internally and encode/decode only at I/O boundaries with an explicit codec, normally UTF-8. |
Engineering checklist for this stack
- To do: validate CLI inputs before domain operations
- To do: use explicit exit codes and deterministic output
- To do: close files, sessions, and network clients
- To do: separate domain logic from input/printing
- To do: measure large-input memory behavior
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.parametrize(2 ("value", "expected"),3 [("valid", "success"), ("", "validation-error"), ("duplicate", "same-result")],4)5def test_contract(value, expected, service):6 result = service.execute(value)7 assert result.status == expected8
9def test_failure_rolls_back(repository, service):10 repository.fail_next_write()11 with pytest.raises(RepositoryError):12 service.execute("valid")13 assert repository.visible_changes() == []Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?