Design a Small Python Command-Line Application

A command-line interface is an agreement with a caller. It should be clear which values are required, which defaults apply and what a successful result means. This workshop builds a fictional visit-time checker. It receives invented durations and counts those within a limit. It reads no attendance records, opens no account and does not launch a website or external service.

Documentation boundary

The Python 3.12 argparse reference documents argument specifications, type conversion, choices and parse_args. It also permits passing a list of strings directly to parse_args. The worked checks use that form, so they do not read the host process’s command-line arguments.

Define the interface before the code

The fictional tool accepts one or more durations in whole minutes. An optional limit defaults to ten. An optional format is either count or values, defaulting to count. Durations and the limit must be nonnegative. A duration exactly equal to the limit is included. Decide these rules before writing the filtering expression; otherwise a boundary result could appear correct under two incompatible interpretations.

Argument example Expected answer What it checks
4 11 7 --limit 10 2 Two durations within limit
4 11 7 --format values 4,7 Preserve accepted order
4 --limit 0 0 Empty accepted result
ten Reject Invalid numeric input
4 --format chart Reject Unsupported presentation

The argument strings in the worked code are separate list items. Your task is to implement the interface and give each error a meaningful boundary. Numeric parsing belongs at input interpretation. Negative-value rejection belongs to this tool’s contract. Formatting belongs after the calculation, so the same accepted values can support both output styles.

Worked interface and answer

import argparse

def run(argv):
    parser = argparse.ArgumentParser(prog="visitcheck", allow_abbrev=False)
    parser.add_argument("minutes", nargs="+", type=int)
    parser.add_argument("--limit", type=int, default=10)
    parser.add_argument("--format", choices=["count", "values"], default="count")
    args = parser.parse_args(argv)
    if args.limit < 0 or any(x < 0 for x in args.minutes):
        parser.error("minutes and limit must be nonnegative")
    kept = [x for x in args.minutes if x <= args.limit]
    if args.format == "values":
        return ",".join(map(str, kept))
    return str(len(kept))

assert run(["4", "11", "7", "--limit", "10"]) == "2"
assert run(["4", "11", "7", "--format", "values"]) == "4,7"
assert run(["4", "--limit", "0"]) == "0"
from contextlib import redirect_stderr
from io import StringIO
for bad in [["ten"], ["4", "--format", "chart"], ["-1"]]:
    try:
        with redirect_stderr(StringIO()):
            run(bad)
    except SystemExit as error:
        assert error.code == 2
    else:
        raise AssertionError("invalid invocation accepted")
print(run(["4", "11", "7", "--limit", "10"]))

The ordinary answer for four, eleven and seven with a limit of ten is the string two. Values mode returns four and seven in their original order, separated by a comma. The function returns presentation text rather than printing internally, which makes its behaviour easy to inspect. A surrounding script could print that returned result after calling run with its own argument list.

No file is required for these checks. The provided lists represent an invocation in a reproducible way and avoid accidental interaction with arguments supplied by an editor or notebook launcher. To try a different case, change one list in your local scratch copy. Keep the initial checks so the default interface remains documented while you explore another input.

Diagnose interface mistakes

If a value of ten is excluded, inspect the comparison boundary rather than changing the default limit. If values mode returns a sorted sequence, check whether an unnecessary sorting step altered the order contract. If an unknown format silently produces count mode, the interface has failed to distinguish a valid request from a typo. These are observable errors even when the filtering arithmetic itself is correct.

A negative limit is not a useful way to represent no accepted visits under this contract. It is an invalid request. Contrast it with a valid limit of zero and a duration of four, which produces a legitimate zero count. Your error table should preserve this distinction, just as the CSV workshop distinguishes invalid content from a genuine zero observation.

Prepare a concise usage note

Write a usage note containing the required durations, both optional arguments, their defaults and one example per output mode. Include the equality boundary explicitly. Then give a reviewer three invocations on paper and ask them to predict the answer without opening the implementation. If they cannot, revise the interface description before adding another feature.

For an extension, specify a summary mode reporting accepted and total counts, such as two of three. Add it as an explicit new choice and retain both original modes. Do not change count mode to return a sentence without recording the interface change, because a caller expecting a numeric string would then receive something else. The exercise is complete when your usage note, decision table and observed outputs agree.

Questions for this exercise

Can parse_args take an explicit list?

Yes. The documented list-of-strings form is used for the deterministic checks instead of reading process arguments.

Is an empty accepted result an error?

No. A valid input may produce zero accepted durations; invalid input is a different outcome.

Does this page launch the application?

No. The snippets are inert text for independent local study, with no embedded command execution.

Official documentation

Explore the Courses overview or use Contact for general enquiries. This is an original INTIAU editorial self-study exercise; no qualification is awarded.

Related guides

View the study diagram
Four cards separate parsing, validation, calculation and presentation for a fictional visit-time command-line exercise with two output modes.
Original explanatory diagram; consult the linked official guidance for current requirements.

Privacy choices

Optional analytics, advertising measurement and personalisation, and hosting telemetry stay off until you accept. Essential sign-in, security and application tools remain available. You can change this choice at any time.

Read our privacy policy