Project: a tested command-line application
Create a command that accepts study-minute values, validates the requested operation and prints a deterministic summary. The goal is a testable application boundary rather than a parser hidden inside business logic.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 40 minutes; optional deep dive: 25 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Translate requirements into contracts
- Implement and test a complete small slice
- Explain production gaps and next increments
Project brief and review
Create a command that accepts study-minute values, validates the requested operation and prints a deterministic summary. The goal is a testable application boundary rather than a parser hidden inside business logic. Reading time does not include your independent implementation time.
Requirements
- Parse explicit arguments with argparse.
- Reject negative minute values.
- Keep the aggregation a pure function.
- Document exit behaviour for invalid input.
Acceptance checklist
These self-checks are page-local, not saved or automatically judged.
Further increments
- Package a console entry point using pyproject.toml.
- Test installation and one real CLI invocation in a clean environment.
Build this as a multi-file project: Tested command-line application
A source-level standard-library command with an actual cli.py adapter. The deterministic contract deliberately has no help action; --help is an invalid argument. Package building, installation and a console entry point remain unsupported further increments. The lesson's single-file browser runner does not import these files.
- Preview and download the starter. In Standalone Playground, sign in and choose Import JSON as a new local project. Importing replaces local editor files only after its existing unsaved-edit confirmation; export your work first.
- Implement total_minutes(values) in totals.py as a pure exact-integer sum. Reject booleans, floats, strings and negative values. Empty input returns integer zero; preserve duplicates, zero and caller input.
- Implement build_parser(), run(arguments), command_outcome(arguments) and main(arguments, stdout, stderr) in command.py. Use explicit argparse arguments, one-or-more integers and no help action. The quiet outcome tuple is (0, '<sum>\n', '') on success or (2, '', 'Invalid minutes\n') on expected input errors only. cli.py writes the actual channels and exits with that status.
- Implement minute_operation((mode, values)) in transfer.py: sum keeps its exact-int empty identity; mean returns a float, counts duplicates and zero in its divisor, and rejects empty. Preserve input and reject unknown modes. Explain why these source-level process checks do not prove an installed command.
- Save snapshot explicitly, then Run current files to execute
main.py's 9 public standard-library tests. The suite stops at the first failure; the untouched starter raises a realNotImplementedError. Inspect the named failing case, edit and rerun. Add an original test and explain why it would catch a tempting wrong approach. - Stop an active program before changing its baseline. Export current project JSON to keep your exact files; import the original starter as a separate local project to reset, with the same edit-loss confirmation. A saved version can be restored explicitly. Record your saved artifact and limitations separately if private project self-review is enabled.
Public tests are visible and editable, not exhaustive grading or proof that you worked without the reference. No completion, reading milestone or judge acceptance is awarded. Run needs the independently enabled approved Python Playground runtime; if unavailable, source editing/export remains available without a fallback. Frameworks, cloud services, live APIs and persistent database sessions remain unsupported. For local work, download all previewed source files into the same empty folder and run python main.py from that folder in your own Python 3.11+ environment. Downloads do not install Python or provide offline server execution.
References are excluded by default. Including them changes only the new download, never your current lesson or saved project.
Project brief and boundaries
A testable command separates calculation, argument parsing and the executable entry point. Each layer owns a different failure policy.
Understand first
Changing sys.argv or spawning a shell for arithmetic tests makes a simple rule depend on global state and operating-system behavior.
Words you will see
- Argument vector
- An ordered list of command-line argument strings.
- Entry point
- The outer function connecting a command to its environment.
- Exit status
- A number an actual command uses to report success or failure.
Translate requirements into layers
The requested command accepts one or more minute values and sums them. argparse parses explicit strings; the pure calculation accepts exact nonnegative integers. Missing arguments and malformed integer text are parser failures. Negative integers parse successfully but violate the domain rule.
Implement the pure sum with empty and invalid cases first. Build the parser next, then an entry adapter returning an outcome. Keep tests independent of global argv. The sample shows a pure sum with borrowed input; its empty result is a calculation identity, not permission for the command to omit required arguments.
Distinguish application evidence
The browser can pass a list of strings to an in-process parser. It cannot prove a console entry point was installed or a shell received the intended exit status. Plan those local checks only after the pure and parser contracts are reliable.
A returned integer and printed digits are different interfaces. Unit tests should assert the return value and type, then test output formatting separately. Do not clamp negative input to zero or catch unexpected programming exceptions as if they were normal user mistakes.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def total_minutes(values):Expose a calculation that needs no command line.
if any(type(value) is not int or value < 0 for value in values):Validate the domain values before summing.
return sum(values)Return a number rather than printing within the core.
print(values)Observe the caller's list remains unchanged.
Create a command that accepts study-minute values, validates the requested operation and prints a deterministic summary. The goal is a testable application boundary rather than a parser hidden inside business logic.
Conceptual command responsibilities, not a spawned shell
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Explicit stringsargparse owns syntax and required-argument errors.
- Pure calculationValidate allowed values and return an integer.
- Entry adapterChoose stdout, stderr and status; installed-command checks remain local work.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reject a boolean.
Try: Change 0 in values to True.
The pure function raises ValueError despite bool being an int subclass.
Try the calculation identity.
Try: Replace values with [].
The pure calculation prints zero; a required CLI parser would still reject no arguments.
Before you move on
May the core return zero for [] while the command rejects an empty argument vector?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. Those are different contracts: an empty sum is defined, but the command promises at least one explicit user value.
Design a testable slice
A parser should accept an explicit argument list in tests. Parsing and domain validation must agree without sharing global state.
Understand first
You can reproduce missing, malformed and valid arguments deterministically without editing sys.argv or launching another process.
Words you will see
- argparse
- Python's standard-library command-line parser.
- Positional argument
- A value supplied by position rather than a named option.
- nargs
- A parser setting specifying how many values an argument takes.
Use a narrow parser interface
add_argument with type=int converts tokens, and nargs='+' requires at least one token. parse_args(arguments) reads the supplied list rather than the process arguments. It creates a namespace whose minutes field is a list of converted integers.
The sample parses two strings, including zero, and displays both parsed values and the original list. The parser owns its namespace and new values list. Keep the caller's argument vector unchanged so another test or adapter can reuse it.
Test error paths deliberately
Normal argparse usage reports invalid syntax to stderr and raises SystemExit with status 2. That is not ValueError from the calculation. Capture those outputs for unit tests or override the parser's error method in an in-process boundary that returns a documented outcome.
Keep help and usage behavior separate from business rules. Browser parsing proves only the in-process path. A real command still needs a main guard, installed entry point, stdout/stderr checks and exit behavior verified locally without exposing sensitive raw arguments.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
parser = argparse.ArgumentParser(prog="study")Name the command explicitly for stable usage text.
parser.add_argument("minutes", type=int, nargs="+")Require at least one integer token.
parsed = parser.parse_args(arguments)Parse only the provided vector.
print(arguments)Confirm the source strings remain available unchanged.
Define a calculation function, a parser builder and an entry function that accepts an argument list. Catch expected input errors only at the CLI boundary and preserve real programming errors. A unit-testable parser can use deterministic argument fixtures.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add an integer token.
Try: Append "8" to arguments.
parsed.minutes includes 8; the parser still does not sum.
Try malformed syntax.
Try: Change "12" to "twelve".
argparse emits a diagnostic and SystemExit; this is an intentional parser error, not reference output.
Before you move on
The token "-3" parses as an int. Does successful parsing make it an allowed study duration?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Parsing establishes syntax and a numeric type. The domain validation must still reject the negative value.
Test the command without a shell
The preserved command reference exercises parsing and summing in process. It is not yet a packaged executable.
Understand first
A runnable slice proves a narrow contract while leaving installation and operating-system behavior visible as remaining work.
Words you will see
- Namespace
- The object holding values returned by argparse.
- Domain error
- An input value violating a business rule after syntax parsing.
- In-process test
- A call made within the current Python interpreter.
Follow the original call
run builds its parser for each call and parses the supplied arguments. nargs='+' enforces presence and type=int converts text. any detects a negative value before sum runs. The assertions cover zero and a two-value sum, and the final print displays 25.
The brief asks to keep aggregation pure. This short run function uses sum directly; the independent project should extract and test the pure calculation separately. The reference does not document final stderr or exit behavior for negative values: it currently raises ValueError.
Design the next boundary
An outer entry function should catch expected user-input errors, emit a safe diagnostic and choose a documented nonzero status. Leave programmer mistakes visible. Do not put print or sys.exit inside the pure sum because that couples every caller to CLI policy.
No subprocess, shell or package install is used here. Local build/install and a real invocation are later integration tasks. Passing these assertions does not show wheel metadata, entry-point wiring or portability; keep that evidence separate from arithmetic correctness.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def run(arguments):Accept explicit caller-owned argument strings.
values = parser.parse_args(arguments).minutesRetrieve converted integers from the namespace.
if any(value < 0 for value in values):Apply the domain constraint after parsing.
return sum(values)Return the calculation without terminating the interpreter.
The command's calculation and parser are exercised through an explicit argument array. No subprocess, package installation or global argument mutation is needed for these unit checks.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Include zero.
Try: Change the final run arguments to ['0', '15'].
The displayed total becomes 15; zero is not omitted as missing.
Trigger required-argument handling.
Try: Change the final call to run([]).
argparse raises SystemExit and emits usage rather than returning an empty sum.
Before you move on
What happens if run receives ['2', '-1'] in the preserved source?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Both tokens parse, then the negative check raises ValueError before sum returns. No final total is returned.
Specify arguments, calculation and executable outcomes
The command accepts one or more integer study-minute values, rejects negatives, and produces their sum. Separate a pure calculation, a parser builder, and an entry function accepting an argument list. The executable adapter owns stdout, stderr, and exit status; the domain layer owns minute validity. Document whether zero is allowed, what missing arguments mean, and whether machine-readable output contains only the number. These decisions let tests distinguish correct behavior from incidental argparse presentation.
The reference run function parses explicit arguments, checks for negatives, and returns a sum. It verifies zero and the pair 10 and 15, then prints 25. This is a useful in-process slice but still combines parsing and summation, leaving a further separation exercise. It neither creates a package nor launches a subprocess. A ValueError for negatives in this helper is not yet a user-facing nonzero exit policy with a safe stderr diagnostic.
Implement numbered layers with immediate tests
1. Write a pure total function and test zero, repeated values, and invalid domain inputs under its declared type contract. 2. Build the parser and pass explicit argument arrays. 3. Add a main-style boundary that translates expected user errors to documented exits. 4. Wire execution behind a main guard. 5. Add package metadata and a console entry point only when the source-level behavior is stable and well tested.
Do not mutate sys.argv in ordinary unit tests or launch a shell merely to exercise addition. Keep unexpected programming exceptions visible rather than converting every failure to an invalid-input message. Test help and missing positional arguments as parser behavior, including the runner's expected SystemExit handling. Distinguish usage errors from domain errors internally even if the public command intentionally maps both to the same failure exit category.
Build a unit-to-installed-command acceptance ladder
Pure-function tests establish the sum and range rules. Parser tests cover valid integers, noninteger text, no arguments, and help. Boundary tests capture stdout and stderr separately, verifying deterministic success output and no success-shaped value on rejection. Include a negative value mixed with positives so the implementation cannot silently filter bad input. Assert that tests do not depend on order or shared global argument state.
For integration, build a distribution, install it into a fresh environment, and run the installed command from outside the checkout. Verify command resolution, the console entry point, supported Python compatibility, help, a valid invocation, and a nonzero invalid invocation. Inspect distribution contents and dependencies. These checks are distinct from the existing argument-array fixture; that fixture does not establish installability, packaging metadata, real process exit behavior, or release readiness.
Design cleanup, compatibility and realistic completion
The numeric core has no external resource to close, which is an intentional simplifying boundary. If file arguments are added, isolate file opening, encoding, size limits, and cleanup in an adapter rather than burdening sum tests with disk access. Keep successful stdout suitable for pipelines and place bounded safe diagnostics on stderr. Avoid echoing complete sensitive argument values in errors. Define interruption behavior before adding long-running work that could emit a partial result.
Plan separate practice blocks for domain tests, command behavior, and installed-artifact checks, with time for debugging environmental differences. Work unaided until each layer has a failing acceptance case, then consult the reference to compare reasoning. A completed parser is a milestone, not completion of packaging. Record remaining unsupported versions and adapter behavior honestly. Later changes to output format or exit status should be reviewed as public compatibility changes because scripts may depend on them.
Transfer question: A new --average option must coexist with the current sum output. What contracts and tests should precede implementation?
Define whether sum remains the default, how average is selected, the output precision, and whether zero values affect the divisor. Keep the existing nonnegative integer validation and require at least one value so division by zero is not silently possible. Add pure tests for uneven totals and a single value, parser tests for the option, and executable tests for formatting and exit behavior. Preserve the existing default invocation unchanged. Rebuild and smoke-test the installed artifact if the command surface changes; successful in-process parsing of the new flag does not prove that the released entry point exposes it.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Build before opening the reference
Parse explicit arguments with argparse. Reject negative minute values. Keep the aggregation a pure function. Document exit behaviour for invalid input. Demonstrate the acceptance cases and document any unsupported requirement.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Implement the pure minute sum
Guided increment 1: write the calculation without any parser, print or process exit.
The contract
- Input is a list of exact nonnegative ints; reject bool, floats, strings and negatives with ValueError.
- Return an exact int sum, keeping duplicates and zero; [] returns 0.
- Borrow the input without changing its contents or order. Do not print or use sys.argv.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Sum repeated values
import copy supplied = [0,4,4] before = copy.deepcopy(supplied) result = total_minutes(supplied) expected = 8 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Empty pure identity
import copy supplied = [] before = copy.deepcopy(supplied) result = total_minutes(supplied) expected = 0 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Large nonnegative integer
import copy supplied = [1000000,1] before = copy.deepcopy(supplied) result = total_minutes(supplied) expected = 1000001 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Reject boolean
import copy supplied = [2,True] before = copy.deepcopy(supplied) try: result = total_minutes(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Reject negative
import copy supplied = [2,-1] before = copy.deepcopy(supplied) try: result = total_minutes(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Reject float
import copy supplied = [2.0] before = copy.deepcopy(supplied) try: result = total_minutes(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does implement the pure minute sum support an independent project, and what remains untested?
The pure calculation is reusable by CLI and tests. It takes O(n) validation and summation work for bounded-size numbers and O(1) extra state. Parser errors, stderr and installation are not tested by this increment.
Return an in-process command outcome
Guided increment 2: parse explicit arguments and return a status/stdout/stderr model, without writing channels or exiting.
The contract
- Input is a list of argument strings; use argparse with required one-or-more integer minute tokens and no help action.
- Success is (0, '<sum>\n', ''); missing, malformed, unknown-option or negative input is (2, '', 'Invalid minutes\n').
- Return an exact tuple. Do not print, change sys.argv, spawn a process or mutate arguments; this model does not itself write actual stdout/stderr.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Successful sum
import copy supplied = ["10","15"] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (0,"25\n","") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Missing required token
import copy supplied = [] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (2,"","Invalid minutes\n") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Zero and repeats
import copy supplied = ["0","3","3"] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (0,"6\n","") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Negative domain input
import copy supplied = ["4","-1"] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (2,"","Invalid minutes\n") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Malformed integer
import copy supplied = ["two"] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (2,"","Invalid minutes\n") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
- Unknown option
import copy supplied = ["--other"] before = copy.deepcopy(supplied) result = command_outcome(supplied) expected = (2,"","Invalid minutes\n") assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does return an in-process command outcome support an independent project, and what remains untested?
Explicit argv and a quiet parser make outcomes deterministic. Processing is O(n) in tokens and values with O(n) parsed storage. Actual stream routing, exit status, help behavior and installed entry points remain local integration work.
Add an explicit mean mode
Transfer: dispatch between sum and mean while preserving validation and the sum contract.
The contract
- spec is (mode, values), where mode is exactly 'sum' or 'mean' and values is a list of exact nonnegative ints.
- sum returns exact int including 0 for empty. mean returns exact float and rejects empty. Unknown mode or invalid values raise ValueError.
- Keep repeated and zero values in the denominator; do not mutate inputs, print, evaluate source text or read global arguments.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Mean with repeated values
import copy supplied = ("mean",[0,6,6]) before = copy.deepcopy(supplied) result = minute_operation(supplied) expected = 4.0 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Empty sum
import copy supplied = ("sum",[]) before = copy.deepcopy(supplied) result = minute_operation(supplied) expected = 0 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Integral mean is float
import copy supplied = ("mean",[6]) before = copy.deepcopy(supplied) result = minute_operation(supplied) expected = 6.0 assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Empty mean fails
import copy supplied = ("mean",[]) before = copy.deepcopy(supplied) try: result = minute_operation(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Unknown mode
import copy supplied = ("median",[2]) before = copy.deepcopy(supplied) try: result = minute_operation(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Boolean values fail
import copy supplied = ("sum",[True]) before = copy.deepcopy(supplied) try: result = minute_operation(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does add an explicit mean mode support an independent project, and what remains untested?
The changed mode adds a denominator and an empty failure boundary. Work is O(n) with constant extra calculation state for bounded-size values. It adds no CLI option or package metadata; implement those separately for a real command.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneProduction hardening is separate
An outcome value can model a command boundary in process: status, normal output and error output are separate fields.
Understand first
You can check routing and formatting without invoking a shell or exiting the browser interpreter.
Words you will see
- stdout
- The normal output channel of an actual command.
- stderr
- The diagnostic output channel of an actual command.
- Outcome model
- A returned value describing intended boundary behavior without executing a process exit.
Make the boundary observable
Choose status zero with a total line for success and status two with a short diagnostic for invalid user input. An in-process entry helper can return a tuple of those fields. This models behavior; a later executable adapter must actually write the channels and return the status.
The sample formats already-validated totals. It makes newline spelling explicit and demonstrates why stdout should stay empty on failure. Avoid printing a partial or default zero report after an input error; consumers might treat that as a valid result.
Scope the remaining local work
Packaging needs pyproject metadata, a chosen console entry point and clean-environment installation checks. Do not install packages inside browser teaching samples or spawn a system process to test the sum. Keep standard-library unit evidence independent of release infrastructure.
Test actual stream routing and exit status in the local executable layer when that layer exists. No returned tuple proves a shell received anything. Document this gap rather than hiding it behind a green unit check or claiming an installed application is complete.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def outcome(total, error=None):Model an outer boundary rather than a pure sum.
if error is not None:Distinguish an explicit error from a valid zero total.
return (0, f"{total}\n", "")Format success output with a terminal newline and no diagnostic.
print(outcome(None, error="negative"))Inspect the failure tuple, not a real process exit.
Add stderr diagnostics and explicit exit codes in the actual executable adapter. Avoid logging sensitive paths or records. A successful in-process fixture is not evidence that a wheel installs correctly; add build/install checks before publishing.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Inspect a valid zero.
Try: Change outcome(25) to outcome(0).
It models success with '0\n'.
Change the success presentation.
Try: Add a label inside the success f-string.
Only normal output changes; existing consumers and exact-output tests may need a deliberate contract revision.
Before you move on
If total is zero and there is no error, should the command's normal-output field be empty?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Zero is a valid result. The success outcome contains "0\n", an empty diagnostic and status zero.
Review and transfer
Adding an average mode changes output semantics and the empty-input boundary, even if argument parsing looks familiar.
Understand first
A sum can use zero as an empty identity. An average needs a count and cannot divide by zero.
Words you will see
- Mode
- A selected operation with its own contract.
- Mean
- The sum divided by the number of values.
- Dispatch
- Choosing an operation from an explicitly allowed name.
Specify the changed requirement
For a transfer, add a mean operation while keeping sum unchanged. Decide whether mean returns float even for an integral result and whether empty values fail. In the guided transfer here, mean returns float and rejects empty input; unknown modes also fail.
Do not use eval to select arbitrary expressions from input. Use a short allowed-mode branch, validate values once, then calculate. Test sum and mean on the same repeated and zero-containing values to show the change is semantic rather than just renaming a function.
Rebuild and explain independently
The sample calculates a mean without parser concerns. It creates no output containers and leaves the input list alone. O(n) validation and summing take linear work for n bounded-size integers; extra calculation storage is constant aside from input and output.
Close the reference and implement the new mode with your own acceptance cases. Browser tests cover the pure operation and in-process outcome only. New CLI options, help, installed-command behavior and compatibility documentation need separately verified local work; transfer completion is not deployment completion.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if not values:Reject the undefined empty mean before division.
raise ValueError("Mean needs values")Make the empty policy explicit.
return sum(values) / len(values)Divide the total by the number of sessions, preserving repeats.
print(type(mean_minutes([6])).__name__)Observe a float even for a whole-number mean.
After implementation, explain the boundary cases and change one requirement without rewriting unrelated behaviour. Package a console entry point using pyproject.toml. Test installation and one real CLI invocation in a clean environment. Keep a record of what you tested; a viewed reference is not proof you independently completed the project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Repeat the largest value.
Try: Use [0, 10, 20, 20] in the first call.
The mean becomes 12.5; repeated values are retained.
Test no observations.
Try: Pass [] to the first call.
The explicit ValueError appears instead of division by zero or a fabricated zero mean.
Before you move on
What is the mean of [0, 6, 6], and why is dividing by two wrong?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It is 4.0: twelve minutes across three values. Deduplicating first would change the number of sessions and the question.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.