CS
303e - Python Style Guide
Code Layout
- Indentation: Use 4 spaces per indentation level, or some
consistent number of spaces. Two spaces is probably not enough, more
than 6 is probably too many.
- Tabs or Spaces: Never, ever, mix tabs and spaces.
- Limit lines to 79 characters. This avoids line wrapping. Use a
line continuation character if necessary.
- Blank lines: Use blank lines before and after a function
definition, and to separate segments of code. Blank lines should be
used to increase readability of your code. Do not separate every two
statements by a blank line.
- Whitespace:
- Do not use extra whitespace inside brackets and braces:
- Do this: myFunction(a[2], {1, 2})
- Not this: myFunction( a[ 2 ], {
1, 2})
- In a function call, do not separate the function name and its
argument list by whitespace:
- Do this: myFunction(1)
- Not this: myFunction (1)
- Use a blank space before and after the = sign in an assignment
statement: i = i+1
- Do not include multiple statements on the same line. This
reduces readability.
- Separate an in-line comment from the statement by at least 2
blank spaces:
- i = i+1 # add 1 to i
- Don't do this: i = i+1#add 1 to i
Import Statements
- Imports should always be on separate lines.
DO THIS:
import os
import sys
NOT THIS:
import sys, os
Comments
- Use a couple of comments before a function or module to briefly
describe what the function (or module) does. Likewise, before a chunk
of related statements, include comments that describe briefly what the
chunk does.
- Don't use too many in-line comments. If you feel a need for them,
you probably aren't using enough comments at the beginning of functions
and complicated code segments.
Naming Conventions
- We will use different naming styles, depending on what we are
naming - a variable, a function, a class. We will talk more about these
in class - use the convention that we discuss in lecture. There are
some common naming conventions:
- concatenated nouns, in which the first noun starts with a
lowercase letter, and the other nouns start with an uppercase letter
- Identifiers that use this convention: myLastName,
myFavoriteHorrorMovie, firstNumber
- Uppercase words separated by underscores - typically used for
constants
- Identifiers using this convention: NUMBER_OF_LEGS,
SIDES_OF_POLYGON
- concatenated letters that begin with capitals
- Identifiers using this convention: SockDrawer, FavoriteNumber
- Use meaningful names. Except for a loop index, it's rarely a good
idea to have a variable i or a variable x. An identifier's name should
give the reader a clue about what it represents.