COMP 141: Coding Style

Just like when writing in English, using good style when writing in a programming language is important because it helps you and other people read your code. Easily-readable code is important for you so you can maintain it (update it later), and for other people so they can figure out what it does as easily as possible, and possibly change it.

Comments

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: For example, this might look like:
# Name: Professor Kirlin
# Date: September 1, 2018
# Class: COMP 141
# 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. 
#     The user types commands to Skynet such as "launch probe" or "send 
#     Terminator back in time." The program reports back details such as 
#     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: 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