Coding Guide

How to Comment and Document Code for Programming Assignments

What good comments explain, how to write docstrings, file headers and a README, comment syntax by language, and what markers look for when they grade documentation.

Updated October 2026 · 7 min read

To comment and document code well, explain why the code does what it does, not what each line says. Markers use your comments to judge whether you understand your own solution.

This guide shows what good comments contain, a before and after example, how to write docstrings and file headers, what goes in a README and the mistakes that cost marks. It ends with a submission checklist and how STEM Donkey can help.

The Three Layers of Well-Documented Code

Good documentation has three layers. Clear names make each line readable. Docstrings or header comments explain what each function or class does, its inputs, outputs and errors. Inline comments explain the reasons behind non-obvious decisions.

On top of that, a README tells someone how to build, run and test the project. If a marker can run your code and understand it without asking you anything, it is well documented.

What Good Comments Explain

The code already shows what happens. Comments add the information the code cannot carry on its own.

  • Intent: the purpose of a block, such as "remove duplicates while keeping first-seen order".
  • Reasons: why you chose one approach over an obvious alternative.
  • Assumptions: conditions the code relies on, for example "input list is already sorted".
  • Units and ranges: "timeout in seconds", "probability between 0 and 1".
  • Known limits: cases the code does not handle, and why.
  • References: the algorithm or source you followed, such as a textbook section.

Before and After: The Same Function Three Ways

Here is one small Python function documented badly, excessively and well.

Under-Documented

def f(a, t):
    r = []
    for x in a:
        if x > t:
            r.append(x)
    return r

It works, but a reader has to decode every name to see the purpose.

Over-Commented

def f(a, t):
    r = []            # make an empty list
    for x in a:       # loop over a
        if x > t:     # if x is bigger than t
            r.append(x)  # add x to r
    return r          # return r

Every comment repeats the code. It adds length without adding understanding.

Well Documented

def readings_above(readings, threshold):
    """Return the readings strictly greater than threshold.

    Args:
        readings: list of sensor values in degrees Celsius.
        threshold: cut-off value in degrees Celsius.

    Returns:
        A new list, in the original order.
    """
    return [r for r in readings if r > threshold]

Clear names remove the need for inline comments, and the docstring states the units, the strict inequality and the order of the result.

Naming Does Half the Work

The cheapest documentation is a good name. Rename before you comment.

UnclearClearWhy it is better
delapsed_daysStates the quantity and the unit
temptemperature_c or swap_valueRemoves the ambiguity of "temp"
flagis_validA boolean reads as a yes or no question
process()remove_outliers()Says what the function actually does
list1, list2students, gradesDescribes the contents

Follow your language's conventions: snake_case for Python functions, camelCase for Java methods, PascalCase for classes in both.

Function and Class Documentation

Every public function, method and class should have a docstring or documentation comment. Use the format your course or language community expects.

  • Python: a triple-quoted docstring as the first statement, often in Google or NumPy style. Tools such as help() read it.
  • Java: a Javadoc comment starting with /** above the method, with @param, @return and @throws tags.
  • C and C++: a block comment above the function, or Doxygen-style comments if your course uses Doxygen.
  • JavaScript: JSDoc comments with @param and @returns.

Javadoc example.

/**
 * Returns the arithmetic mean of the given scores.
 *
 * @param scores array of exam scores, each from 0 to 100
 * @return the mean score
 * @throws IllegalArgumentException if scores is empty
 */
public static double mean(int[] scores) {
    if (scores.length == 0) {
        throw new IllegalArgumentException("scores is empty");
    }
    long total = 0;   // long avoids overflow on very large arrays
    for (int s : scores) {
        total += s;
    }
    return (double) total / scores.length;
}

The single inline comment explains a decision (using long), which a reader might otherwise question. The cast to double prevents integer division.

File Header Comments

Many courses ask for a header at the top of each source file. Keep it short and factual.

# File:     inventory.py
# Purpose:  Track stock levels and flag items below reorder point.
# Course:   CS101, Assignment 3
# Usage:    python inventory.py stock.csv
# Notes:    Requires Python 3.10 or later.

Include your name or student number only if your course requires it. Avoid change logs in the header; version control records history better.

Writing a README

A README is the first file a marker opens. It should let them run your work in a few minutes.

SectionWhat to write
OverviewOne or two sentences on what the program does
RequirementsLanguage version and any libraries, with install commands
How to runExact commands and an example input
How to testThe command that runs the tests and what success looks like
Design notesMain files, data structures and any assumptions
Known limitationsWhat does not work yet, stated honestly

Documenting Tests

Tests are documentation too: they show exactly what the code is meant to do. Give each test a descriptive name and, where useful, a one-line comment on the case it covers.

def test_readings_above_excludes_equal_values():
    # threshold itself is not "above", so 20.0 is dropped
    assert readings_above([19.5, 20.0, 21.2], 20.0) == [21.2]

Comment Syntax by Language

LanguageSingle lineBlock or documentation
Python# comment"""docstring"""
Java// comment/* block */ and /** Javadoc */
C and C++// comment/* block */
JavaScript// comment/** JSDoc */
R# comment#' roxygen2 comments
MATLAB% comment%{ block %}
SQL-- comment/* block */

Common Documentation Mistakes

  • Restating the code: "increment i" above i += 1 tells the reader nothing.
  • Out-of-date comments: a comment that contradicts the code is worse than none. Update comments when you change logic.
  • Commented-out code left in: delete it before submission.
  • No docstrings on public functions: markers often check these specifically.
  • Jokes or frustration in comments: keep the tone professional.
  • A README that does not run: test your own instructions on a clean copy of the project.

A steady habit helps more than a last-minute pass. Documenting each function as you write it is a lighter load than documenting forty at once at midnight.

What Markers Look for, and a Submission Checklist

Rubrics vary, but documentation marks usually reward the same few things. Knowing them lets you spend effort where it counts.

CriterionWhat earns the marks
ReadabilityDescriptive names, consistent style and sensible function length
API documentationDocstrings that state inputs, outputs, units and errors
Explanation of designComments or a README section that justify key choices
ReproducibilityRun and test instructions that work first time
Honesty about limitsKnown issues stated clearly rather than hidden

Before you submit, work through this list.

  1. Every public function and class has a docstring with inputs, outputs and errors.
  2. Inline comments explain reasons, assumptions and units, not syntax.
  3. Names are descriptive and follow the language's conventions.
  4. Each file has the header your course requires.
  5. The README's run and test commands work on a clean copy.
  6. No commented-out code, debug prints or stale comments remain.

How STEM Donkey Helps with Code Documentation

Send the assignment specification, your language and version, and any style guide your course uses. A writer prepares custom, tested code with docstrings, focused inline comments, file headers and a README, or documents and tidies code you have already written.

Use it to see what well-documented code looks like, then apply the same habits to your own work. Free revisions within the scope of your original request are included.

Want Code That Explains Itself?

Send the specification and your language. You get custom, tested code with docstrings, focused comments and a README that tells a marker how to run it.

Order Your Programming Assignment

Free revisions · Full refund if late · Written from scratch for your order

Frequently Asked Questions

How many comments should my code have?

There is no fixed ratio. Every public function needs a docstring, and inline comments belong wherever a reader would ask "why?". Clear code with good names needs fewer comments.

What is the difference between a comment and a docstring?

A comment is ignored by the language and explains code to readers. A Python docstring is a string stored with the function, which tools such as help() and documentation generators can read.

Should I comment every line?

No. Line-by-line comments usually repeat the code. Comment blocks of logic and non-obvious decisions instead.

Do comments slow my program down?

No. Compilers and interpreters ignore comments, so they have no effect on running speed.

Which docstring style should I use in Python?

Use the one your course specifies. If none is given, Google style and NumPy style are both widely used. Pick one and use it consistently.

Do I need a README for a small assignment?

If the brief asks for one, yes. Even when it does not, a short README with run instructions makes marking easier.

Should comments be written in full sentences?

Docstrings and block comments read best as full sentences. Short inline comments can be brief phrases.

Can you document code I have already written?

Yes. Send your code and the brief. A writer can add docstrings, comments and a README, and point out unclear names.