Python PEP8 Style Guide

definitions
python
style-guide

A PEP (Python Enhancement Proposal) is a design document describing conventions for how to style code. This course follows Google’s PEP, a variant of PEP8.

Variable and function names

Names must start with a letter (not a digit) and can otherwise only contain letters, digits, and underscores (_). Names should be lowercase, with words separated by underscores for readability:

Yes No
descriptive_variable_name DescriptiveVariableName

Spacing

Put single spaces around binary operators; don’t pad the inside of brackets:

Yes No
i = i + 1 i=i+1
hypot2 = x*x + y*y hypot2 = x * x + y * y
c = (a+b) * (a-b) c = (a + b) * (a - b)

Breaking long lines

All lines should be strictly less than 80 characters wide. Wrap a long expression in a redundant enclosing bracket so it can be split across multiple lines (otherwise pressing enter would evaluate the expression early):

>>> income = (gross_wages
...           + taxable_interest
...           + (dividends - qualified_dividends)
...           - ira_deduction
...           - student_loan_interest)

Comments

Anything following a # is ignored by Python. Comments (and docstrings, see python-functions) should explain why something not obvious was done, not simply restate what the code already shows:

x = x + 1   # Not helpful: Increment x
x = x + 1   # Helpful: Compensate for border