How to Comment and Document Code for Programming Assignments

Code that works but cannot be understood loses marks, and in the workplace it loses time. This guide shows what good comments explain, how to write docstrings and header comments, what belongs in a README, and how to document code the way markers and teams expect.

PythonJavaJavaScript C / C++DocstringsREADME

Most programming rubrics award marks for readability and documentation, often 10 to 20 percent of the grade. Markers read dozens of submissions, and they reward code they can follow quickly. Beyond grades, documentation is a professional habit: the next person to read your code, including you in six months, needs to understand what it does and why.

Good documentation does not mean more comments. It means the right comments in the right places, clear names that reduce the need for comments, and a short written explanation of how to run and understand the program.

What Good Comments Explain

The code already says what it does, line by line. Comments should explain what the code cannot: intent, reasoning and context.

Comment typeExplainsExample
WhyThe reason behind a decision# Sort first so binary search can be used below
IntentThe purpose of a block# Remove duplicate student IDs before calculating averages
AssumptionsConditions the code relies on# Assumes the input list is non-empty
Non-obvious logicTricky algorithms or formulas# Use (low + high) // 2 avoids float indices
WarningsLimitations or edge cases# Not thread-safe; call from the main thread only

The test: if deleting a comment would lose no information that the code itself does not already show, the comment is noise. "i = i + 1 # add one to i" is the classic example.

Before and After

Under-documented

def calc(l, t):
    r = []
    for x in l:
        if x[1] >= t:
            r.append(x[0])
    return r

Over-commented

def calc(l, t):
    r = []            # make an empty list
    for x in l:       # loop over l
        if x[1] >= t: # check if x[1] is at least t
            r.append(x[0])  # add x[0] to r
    return r          # return r

Well documented

def students_meeting_threshold(scores, threshold):
    """Return the names of students whose score meets the threshold.

    Args:
        scores: list of (name, score) tuples.
        threshold: minimum passing score, inclusive.

    Returns:
        List of names, in the original order.
    """
    return [name for name, score in scores if score >= threshold]

The improved version needs almost no inline comments because the names explain themselves, and the docstring tells a caller exactly what to pass in and what comes back.

Naming Does Half the Work

When you find yourself writing a long comment to explain what a block does, consider extracting that block into its own function with a descriptive name. A call such as remove_duplicate_ids(records) documents itself, can be tested on its own and keeps the calling function short enough to read at a glance. Markers often reward this kind of decomposition under both readability and design criteria.

Function and Class Documentation

Every public function, method and class should have a documentation comment describing its purpose, parameters, return value and any errors it raises.

LanguageConventionFormat
PythonDocstrings (PEP 257), often Google or NumPy styleTriple-quoted string as the first line of the function
JavaJavadoc/** ... */ with @param, @return, @throws
JavaScript / TypeScriptJSDoc/** ... */ with @param {type} and @returns
C / C++Doxygen-style comments/** ... */ or /// with @brief, @param, @return
C#XML documentation comments/// <summary> ... </summary>

Javadoc example

/**
 * Calculates the monthly repayment on a fixed-rate loan.
 *
 * @param principal  amount borrowed, must be positive
 * @param annualRate interest rate as a decimal, e.g. 0.05 for 5%
 * @param months     loan term in months
 * @return the monthly repayment, rounded to two decimal places
 * @throws IllegalArgumentException if any argument is not positive
 */
public static double monthlyRepayment(double principal, double annualRate, int months)

Need help with a programming assignment?

We deliver working, well-documented code with clear comments and a README, in the language your course uses.

Get Coding Help →

Many courses require a header at the top of each source file. Check your course's template; a typical header includes:

# File: inventory.py
# Author: [Your name], [Student ID]
# Course: CS 101, Assignment 3
# Date: 2026-10-07
# Description: Manages a store inventory, supporting adding, removing
#              and searching for items, and reporting low stock.

Some courses also ask you to declare any outside resources or collaborators in this header. Follow your institution's academic integrity rules exactly.

Writing a README

For multi-file projects, a README file explains the project to someone who has never seen it. Markers often read it first.

  1. Project title and summary: one or two sentences on what the program does.
  2. Requirements: language version and any libraries, with install commands.
  3. How to run: exact commands, including example input.
  4. Features: what is implemented, mapped to the assignment requirements.
  5. Design notes: key decisions, data structures and algorithms, and why you chose them.
  6. Known limitations: anything incomplete or any bugs you found but could not fix. Honesty here often earns more credit than hoping the marker misses it.
  7. Testing: how you tested the program and how to run the tests.

Documenting Tests

Tests are documentation too: a well-named test shows exactly how a function is meant to behave. Name each test after the behaviour it checks, such as test_returns_empty_list_when_no_scores_meet_threshold, and group related tests together. For edge cases, a one-line comment explaining why the case matters, such as "a threshold equal to a score should count as a pass", helps markers see that you thought about boundaries. Where your course does not require a testing framework, a short section in the README listing the inputs you tried and the outputs you expected still demonstrates careful work.

Comment Syntax by Language

LanguageSingle lineBlock
Python# commentConsecutive # lines (docstrings are for documentation, not block comments)
Java, C, C++, C#, JavaScript// comment/* comment */
R# commentConsecutive # lines; roxygen2 uses #'
MATLAB% comment%{ ... %}
SQL-- comment/* comment */

In MATLAB, the first comment lines of a function file act as its help text, shown when someone types help functionName, so write them as a proper summary of inputs and outputs.

What Markers Look For

Common Mistakes

Submission Checklist

Frequently Asked Questions

How many comments should my code have?

There is no fixed ratio. Document every function and class, and add inline comments where the reasoning is not obvious. Clear names reduce how many inline comments you need.

What is the difference between a comment and a docstring?

In Python, a comment starts with # and is ignored by the interpreter. A docstring is a string literal at the start of a function, class or module that is stored with it and can be read by help() and documentation tools.

Should I comment every line?

No. Line-by-line comments usually repeat the code and make it harder to read. Comment blocks of logic, decisions and anything non-obvious.

Do comments affect how fast my program runs?

No. Comments are ignored when the program runs, so they have no effect on speed in compiled or interpreted languages.