Program Readability, Organization, and Documentation
Source Code Documentation That Matches the Code
Source Code Documentation is explanatory information stored alongside a program’s instructions to help people understand and maintain it. You use it when calling an unfamiliar function, investigating unexpected behaviour, or changing code someone else wrote. Good documentation records information that names and statements alone leave uncertain: what inputs mean, which conditions callers must satisfy, what results represent, and why a particular decision was made.
Document the function’s promise
A function’s contract connects its inputs to its observable behaviour. Useful documentation answers these questions when they matter:
- What does the function accomplish?
- What input types, units, and limits does it require?
- What does it return, including the result’s type and units?
- Does it change an existing object, print information, or raise an error?
A Python docstring is a string literal placed as the first statement inside a function, module, or class. Triple double quotes are the usual convention. For a function, place the summary first and add details that a caller needs.
Example: A display reports completed minutes from a duration measured in seconds. Its governing rule is
Here, s is a nonnegative integer number of seconds, m is the returned number of minutes, and the floor symbols mean round down to an integer.
def completed_minutes(seconds):
"""Return completed minutes as an integer.
seconds must be a nonnegative integer duration in seconds.
Ignore any remaining seconds.
"""
return seconds // 60For 154 seconds, the function returns 2 minutes. The documentation makes the rounding rule explicit rather than leaving readers to guess whether the result is rounded, truncated, or expressed as a decimal.
Explain decisions near the relevant code
A comment can explain a local decision or constraint. Place it beside the code it explains, where a future reader will encounter both together.
Information to communicate | Suitable location | Example content |
|---|---|---|
Meaning and limits of a function’s inputs | Function docstring | Duration is a nonnegative integer in seconds. |
Meaning of the returned result | Function docstring | Return completed minutes as an integer. |
Reason for a surprising local choice | Nearby comment | Ignore partial minutes because the display reports completed minutes. |
A comment such as # Divide by 60 adds little beside seconds // 60. A comment explaining the display policy records information the expression does not contain. Explain a non-obvious reason rather than repeating an obvious instruction.
Clear names support documentation. For example, seconds communicates more than x, but it does not specify whether negative values are permitted. Use names and documentation together rather than expecting either to communicate everything.
Keep documentation trustworthy
Check each claim against both the intended requirements and the current code. Include relevant boundary behaviour: what happens at zero, exactly at a threshold, or when an input collection is empty? Document side effects when callers need to know about them.
Distinguish an input requirement from an implemented check. The sample function requires nonnegative integer inputs, but it contains no statement that rejects negative values. Its docstring should not promise an error that the code does not raise.
When behaviour changes, review the summary, input limits, units, examples, and nearby rationale together. Update documentation with the behaviour it describes. Removing an obsolete comment can be better than preserving a confident but false explanation.
What to remember
- Document purpose, input requirements, results, and relevant side effects.
- Use docstrings for caller-facing details and nearby comments for local reasoning.
- State units, rounding rules, and important boundaries precisely.
- Check that every promise matches the implemented and intended behaviour.
Example: Documenting a Packing Calculation
A school supply centre packs identical items into crates. Every item must be packed, a partly filled final crate is allowed, and each crate holds at most crate_capacity items. Calls supply a nonnegative integer item_count and a positive integer crate_capacity.
Use Source Code Documentation to improve this function without changing its calculation:
def crates_needed(item_count, crate_capacity):
"""Return the number of full crates."""
return (item_count + crate_capacity - 1) // crate_capacitya) Replace the docstring with an accurate description of the purpose, input requirements, returned result, and zero-item case.
- Establish the function contract: the requirements on callers and the behaviour promised for valid calls. The smallest valid item count is ________, and the smallest valid crate capacity is ________ item per crate. The result is a count of crates, not a count of items.
- Describe what the calculation actually provides. It includes a partly filled final crate when necessary, so the phrase full crates is misleading. For zero items, the numerator is one less than the positive capacity, and integer division returns zero.
A suitable replacement is:
def crates_needed(item_count, crate_capacity):
"""Return the minimum number of crates needed for all items.
item_count must be a nonnegative integer count of items.
crate_capacity must be a positive integer items-per-crate limit.
Return an integer count, including a partly filled final crate.
Return 0 when item_count is 0.
"""
return (item_count + crate_capacity - 1) // crate_capacityThese input requirements do not claim that the function checks or rejects every invalid input.
b) Add one nearby comment explaining why the expression adds crate_capacity - 1 before integer division.
- Ordinary integer division would count only complete groups. For example, dividing 13 items by a capacity of 12 items per crate using // gives 1, which would leave one item unpacked.
- The added amount makes the calculation round upward when there is a remainder, while preserving an exact quotient when the items divide evenly. This is appropriate for nonnegative integer counts and positive integer capacity.
A suitable comment explains the packing reason:
# Include a final crate when any items remain after full crates.
return (item_count + crate_capacity - 1) // crate_capacityThis records why rounding upward is necessary instead of merely saying that a value is added and then divided.
c) Calculate the result for 94 items and a capacity of 12 items per crate. Write a numeric example suitable for the documentation.
- Apply the expression using the supplied item count and capacity. The adjusted numerator is ________.
- Perform integer division. There are eight complete groups of 12 in the adjusted numerator, with a remainder of nine.
- Check the result against the packing requirement. Seven crates can hold only 7×12=84 items, while eight crates can hold 8×12=96 items. Therefore, eight is the minimum number that can hold all 94 items.
The result is 8 crates. A suitable documentation example is: crates_needed(94, 12) returns 8; the final crate contains 10 items.
A descriptive identifier is a code name that communicates the role of a stored value. A school registration program uses the identifiers below, and its names accurately describe their contents. Match each identifier to its intended meaning. A Boolean condition records whether something is true.
Collection of learners' names
Duration measured from a starting time, in seconds
True-or-false indication that access is allowed
Upper limit on the number of sign-in tries
student_names
MAX_LOGIN_ATTEMPTS
elapsed_seconds
has_permission
A scoreboard receives a nonnegative integer duration in milliseconds. Its display policy shows completed seconds and discards partial seconds. Which comment best explains the decision behind the return statement?
def displayed_seconds(elapsed_ms):
return elapsed_ms // 1000