Appendix B: Composing Clear Code


This page complements the official Style Guide for Python Code by providing some recommendations that are appropriate for those who are new to computer programming.



Coding



Naming Conventions

When choosing names for your variables, functions, methods, and classes:

Identifier Naming Rules Examples
Variable A short, but meaningful, name that communicates
to the casual observer what the variable represents,
rather than how it is used. Begin with a lowercase letter
and use camel case (mixed case, starting with lower case).
mass
hourlyWage
isPrime
Constant Variable Use all capital letters and separate internal words
with the underscore character.
N
BOLTZMANN
MAX_HEIGHT
Class A noun that communicates what the class represents.
Begin with an uppercase letter and use camel case for
internal words.
class Complex
class Charge
class PhoneNumber
Function
or Method
A verb that communicates what the function or method
does. Begin with a lowercase letter and use camelCase for
internal words.
move()
draw()
enqueue()


Commenting

Programmers use comments to annotate a program and help the reader (or grader) understand how and why your program works. As a general rule, the code explains to the computer and programmer how the program works; the comments explain to the programmer what the program does. Comments can appear anywhere within a program where whitespace is allowed. Python ignores comments.

A comments begins with # (the pound or number-sign character) and ends at the end of the line on which the # appears. Any text from the # to the end of the line is ignored.

There is no widely agreed upon set of rules. Good programmers write code that documents itself.



Whitespace

Programmers use whitespace in their code to make it easier to read.



Indenting

Programmers format and indent their code to reveal structure, much like an outline. In most modern programming languages, indentation is important to the human reader of the program, but is ignored by the computer. With the Python language, indentation is not ignored by the computer; indentation is part of the program's logic.



Q & A

Q. Are there any official coding standards?

A. Yes. See the Style Guide for Python Code.

Q. Any good references on programming style?

A. The Practice of Programming by Brian W. Kernighan and Rob Pike is a classic.

Q. How can I easily indent my code?

A. Use an editor designed for writing code. For example, in IDLE, if you select a region of code and hit the Tab key, IDLE will reindent it for you automatically.

Q. How can I write unmaintainable code?

A. Here's one guide to designing unmaintainable code.