Comments and documentation

Back to main page

Comments

One of the most important parts of writing good Python code is clarity. In many cases, that clarity is aided by adding comments to the code, meant as human-aid in reading the code which Python safely skips over. For instance, suppose we wrote the following code:

userInput = input('Enter a string: ')
userInput = userInput[::-1]
print(userInput)

To any experienced Python programmer, it’s pretty obvious what this is meant to do. To a newer programmer, though, this might be totally esoteric and require effort to figure out what this does. Now imagine you have a few hundred lines of code like this that are equally as esoteric. It would take awhile just to figure out what on earth the code is supposed to do! Such obscurities can often be clarified with comments:

# Prompt user for input
userInput = input('Enter a string: ')

# Reverse order of letters in string
userInput = userInput[::-1]

# Print reversed string
print(userInput)

Self-documenting code

Another common practice that is used to aid in easy reading of code is self-documenting code. This means you name your variables and functions so that the intent of the code is obvious (or as obvious as possible). When done on the code above, we might rewrite it so it becomes

userInput = input('Enter a string: ')
reversedUserInput = userInput[::-1]
print(reversedUserInput)

Now we can actually guess what the function does just by choosing better variable names. We can do the same thing with functions too:

def reverse_string(s):
    return s[::-1]

userInput = input('Enter a string: ')
reversedUserInput = reverse_string(userInput)
print(reversedUserInput)

Docstrings

In Python, it is conventional to include a docstring after the function declaration. A docstring is a triple-double quotes string that is placed immediately after the function header:

def reverse_string(s):
    """
        Reverse the order of the characters that make up s
    """
    return s[::-1]

The docstring should describe what the function does, including how parameters are used (if any) and what it returns (if it returns anything).

Back to main page