Commenting your code
Commenting your code is an important part of the software development process.
It is critical to document a piece of code, be it a line, a few lines, or a longer
section, with a comment that explains everything necessary to understand the code
that is not immediately obvious by reading it. In other words, if there is
any doubt in your mind about whether a section of code requires a comment, then comment it.
Comments are used to explain code to someone reading your program. That means that a
comment like this
num_users = 30 # This code sets the number of users to 30.
is not particularly useful. The comment is redundant because someone reading your code
can tell that the variable num_users is being set to 30 from the line of code.
Instead, if this is an important line of code, explain why the variable is being set to
30.
Think of comments as explaining to a reader or user what your program is doing.
How much should I comment?
You should include a comment at the top of the whole program (see below) and immediately
before each function definition (see below). You should also include comments
at other critical points in your program where you feel the code warrants further explanation.
Err on the side of commenting too much, rather than too little.
Comments at the top of your program
Every program you write should have the following information at the top
in a comment:
- Your name
- Name of project
- Honor code pledge
- Description of what the program does
- Description of the input to the program (what the user types)
- Description of the output from the program (what the user sees)
For example, this might look like:
# Name: Professor Kirlin
# Project: Skynet
# Pledge: I have neither given nor received unauthorized aid on this program.
# Description: Skynet is a artificial intelligence system which guides
# the global digital defense network. It will not start a nuclear war.
# Input: The user types commands to Skynet such as "launch probe" or "send Terminator back in time."
# Output: The state of the Skynet system after each command, including statistics
# about number of Terminators created, dollars spent, and nuclear wars started (should always be zero).
Comments before each function
Every function (other than main) must have a comment immediately before its definition.
You should include the following information:
- A description of what the function does.
- For each parameter: a description of what the parameter means or controls.
- If the function returns a value, a description of what the return value is.
For example, this might look like:
# This function computes the circumference of a circle.
# Parameters: r, the radius of the circle.
# Returns: the circumference of the circle.
def circumference_of_circle(r):
return 2 * 3.14 * r