Example of Commented Code
Python program without comments
This program has minimal comments. Can you figure out what it does? Would you know who to ask for help if you could not make this code work?
Program4.3.py
# ThinkPython Sample Code - Chapter 4
import sys
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print bob
fd(bob, 100)
rt(bob)
fd(bob, 100)
rt(bob)
fd(bob, 100)
rt(bob)
fd(bob, 100)
wait_for_user()
Python program with comments
In Python everything after a "#" on a given line will be a comment. Comments can be placed above, below and on the same line as the statements being described. Nothing after the "#" will be interpreted by Python, so you can also "comment out" statements during testing and debugging. Python also allows you to create a comment block by enclosing multiple lines of text within triple quotes, """. Software that uses Python scripting to build tools, such as ArcGIS, will try to use these comment blocks as program descriptions within their on-line help systems.
Python4.3.py with comments
#!/usr/env python
"""
Created on September 11, 2008
by Keith Cherkauer
ThinkPython Sample Code - Chapter 4
This program draws a box using the Think Python drawing package
swampy.1.1.
2011-08-28 Modified to add sample comments. KAC
"""
# import required modules
import sys
from TurtleWorld import *
# activate turtle world and start a turtle named "bob"
world = TurtleWorld()
bob = Turtle()
print bob
# draw first side
fd(bob, 100)
rt(bob)
# draw second side
fd(bob, 100)
rt(bob)
# draw third side
fd(bob, 100)
rt(bob)
# draw final side
fd(bob, 100)
wait_for_user() # leave window open until users closes it
Note that the header comment includes information on the author of the code, when the code was created, and a brief summary of what the code does.
Effective in-line comments should document the functionality of code blocks. For example, every function should have a descriptive comment describing functionality (some programs, such as ArcGIS will search Python code for comment blocks in triple quotes and use those to populate the pop-up help screens). Within functions and main code blocks, comments should be added to describe function sections of the code. In general, commenting every line of code is time consuming and not really necessary. It is likely that you will get tired of writing so much and other will get tired of reading those comments, so focus on commenting sections of the code. An exception is that constants and parameters pulled from literature probably deserve their own comments to document sources.