The suite within a compound statement is typically indented four
spaces. It is often best to set your text editor with tab stops every four
spaces. This will usually yield the right kind of layout.
We'll show the spaces explicitly as ␣'s in the following
This is has typical spacing for a piece of Python
Also, limit your lines to 80 positions or less. You may need to
break long statements with a
\ at the end of a line. Also,
parenthesized expressions can be continued onto the next line without a
\. Some programmers will put in extra ()'s just to make line
Names. Function names are typically
However, a few important functions were done in
CapWords style with a leading upper case letter.
This can cause confusion with class names, and the recommended style is
a leading lowercase letter for function names.
In some languages, many related functions will all be given a common
prefix. Functions may be called
inet_ntoa, etc. Because Python has classes (covered
in Part III, “Data + Processing = Objects”) and modules (covered in Part IV, “Components, Modules and Packages”), this kind of function-name prefix is not used in
Python programs. The class or module name is the prefix. Look at the
for guidance on this.
Parameter names are also typically
In the event that a parameter or variable name conflicts with a Python
keyword, the name is extended with an _. In the following example, we want
our parameter to be named
, but this conflicts
with the builtin function
range. We use a trailing _
to sort this out.
def integrate( aFunction, range_ ):
"""Integrate a function over a range."""
Blank lines are used sparingly in a Python file, generally to
separate unrelated material. Typicaly, function definitions are separated
by single blank lines. A long or complex function might have blank lines
within the body. When this is the case, it might be worth considering
breaking the function into separate pieces.
Docstrings. The first line of the body of a function is called a
docstring. The recommended forms for docstrings
are described in Python Extension Proposal (PEP) 257.
Typically, the first line of the docstring is a pithy summary of the
function. This may be followed by a blank line and more detailed
information. The one-line summary should be a complete sentence.
def fact( n ):
"""fact( number ) -> number
Returns the number of permutations of n things."""
if n == 0: return 1L
def bico( n, r ):
"""bico( number, number ) -> number
Returns the number of combinations of n things
taken in subsets of size r.
n -- size of domain
r -- size of subset
The docsting can be retrieved with the
help for interactive help, or
) for help
Here's an example, based on our
Help on function fact in module __main__:
fact( number ) -> number
Returns the number of permutations of n things.