Python Style Guide#

Code is read far more often than it is written. You will read your own code days or weeks later, your teammates will read it, and your instructors and TAs will read it when you ask for help. Consistent formatting makes code easier to read, easier to debug, and easier to share.

Python has an official style guide called PEP 8 (Python Enhancement Proposal 8). It is the standard that most Python programmers follow. This guide covers the parts of PEP 8 you will use most in this course.

Note

PEP 8 is a set of conventions, not laws of nature. The goal is readable code. When a rule makes your code less readable, use your judgment. But while you are learning, follow the rules as written. You need to know them before you can decide when to bend them.

Quick Reference#

Topic

Convention

Indentation

4 spaces per level (never tabs mixed with spaces)

Line length

79 characters max (72 for comments and docstrings)

Functions and variables

snake_case

Constants

UPPER_SNAKE_CASE

Classes

PascalCase

Blank lines

2 around top-level functions and classes, 1 between methods

Imports

Top of file, one per line, grouped and ordered

Comparisons to None

Use is None / is not None

Spaces around operators

Yes: x = a + b

Spaces around = in keyword arguments

No: f(x=5)


1. Indentation#

In Python, indentation is not just style. It defines the structure of your code. PEP 8 asks for 4 spaces per indentation level.

# Good
def check_temperature(temp):
    if temp > 100:
        print("Too hot!")
    else:
        print("Just fine.")
# Bad: 2 spaces here, 8 there, inconsistent everywhere
def check_temperature(temp):
  if temp > 100:
          print("Too hot!")
  else:
    print("Just fine.")

Tips

  • Set your editor to insert 4 spaces when you press the Tab key. Most editors (VS Code, PyCharm, Thonny, IDLE) do this by default for Python files.

  • Never mix tabs and spaces in the same file. Python 3 will raise a TabError if it can’t tell how your blocks line up.


2. Line Length#

Keep lines to 79 characters or fewer. Comments and docstrings should be limited to 72.

Short lines fit side by side in split-screen editors, print cleanly, and are easier for your eyes to follow.

When a line gets too long, break it inside parentheses, brackets, or braces. Python lets you continue a line automatically there.

# Good: continuation lines are indented to show they belong together
total_cost = (unit_price * quantity
              + shipping_fee
              - discount)

result = calculate_stress(
    force=applied_force,
    area=cross_section_area,
    safety_factor=1.5,
)
# Bad: one very long line that runs off the screen
total_cost = unit_price * quantity + shipping_fee - discount + handling_fee + tax_amount - coupon_value

Tip: When breaking a line around a math operator, put the operator at the start of the new line, as in the first example above. It makes it easy to see what is being added or subtracted.


3. Blank Lines#

Blank lines act like paragraph breaks.

  • Two blank lines before and after top-level function and class definitions.

  • One blank line between methods inside a class.

  • Single blank lines inside functions to separate logical steps (use sparingly).

import math


def circle_area(radius):
    return math.pi * radius ** 2


def circle_circumference(radius):
    return 2 * math.pi * radius


class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return circle_area(self.radius)

4. Whitespace in Expressions and Statements#

Use spaces to make expressions easy to scan, but don’t overdo it.

Put a space around these operators: assignment (=), comparison (==, <, >=, etc.), augmented assignment (+=, -=), and boolean operators (and, or, not).

Don’t put spaces:

  • Just inside parentheses, brackets, or braces

  • Before a comma, colon, or semicolon

  • Before the opening parenthesis of a function call or index

  • Around = when used for keyword arguments or default values

# Good
x = 5
y = x * 2 + 1
values = [1, 2, 3]
print(values[0], values[1])
speed = calculate_speed(distance=100, time=9.58)

def greet(name="World"):
    print("Hello,", name)
# Bad
x=5
y = x*2+1
values = [ 1,2 ,3 ]
print (values [0] , values [1])
speed = calculate_speed( distance = 100, time = 9.58 )

def greet(name = "World") :
    print ("Hello,",name)

A note on math: With mixed operators, it is fine (and often clearer) to add spaces only around the lowest-priority operators:

c = (a + b) * (a - b)
hypotenuse = (a**2 + b**2) ** 0.5

Avoid trailing whitespace. Invisible spaces at the end of a line don’t change how the code runs, but they clutter version control diffs. Most editors can strip them automatically on save.


5. Naming Conventions#

Good names are the single most effective way to make code self-explanatory.

What

Style

Examples

Variables

snake_case

student_count, max_temp

Functions

snake_case

compute_average(), read_file()

Constants

UPPER_SNAKE_CASE

GRAVITY = 9.81, MAX_ITERATIONS = 1000

Classes

PascalCase

BankAccount, SensorReading

Modules (file names)

short, lowercase or snake_case

utils.py, data_loader.py

Guidelines for choosing names

  • Be descriptive. voltage_readings beats vr, and average_speed beats x.

  • Use nouns for variables and verbs for functions. total_mass is a value; calculate_total_mass() is an action.

  • Short names are fine in tiny scopes. Loop counters like i and j, or math-style x and y for coordinates, are perfectly normal.

  • Avoid the single letters l (lowercase L), O (capital o), and I (capital i). In many fonts they look like 1 and 0.

  • Don’t reuse built-in names such as list, str, sum, max, input, or id. If you write list = [1, 2, 3], you can no longer use Python’s list() function in that scope.

# Good
MAX_ATTEMPTS = 3
student_scores = [88, 92, 79]

def average_score(scores):
    return sum(scores) / len(scores)

class GradeBook:
    pass
# Bad
maxattempts = 3            # hard to read; is it max-attempts or maxat-tempts?
SS = [88, 92, 79]          # what is SS?
def AvgScore(S):           # functions should be snake_case
    return sum(S) / len(S)
class grade_book:          # classes should be PascalCase
    pass

6. Comments#

Comments explain why the code does something, or what a tricky part is for. They shouldn’t just repeat what the code already says.

Block comments go on their own lines, above the code they describe. Start with # (a hash and a space).

Inline comments go at the end of a line. Use them sparingly. Put at least two spaces before the #.

# Good: explains the reason
# Convert to meters because the sensor library expects SI units.
distance_m = distance_ft * 0.3048

x = x + 1  # Compensate for the border offset

# Bad: repeats the code
x = x + 1  # add 1 to x
#this comment has no space after the hash
y = 10 # only one space before the hash

Keep comments current. A comment that contradicts the code is worse than no comment at all. If you change the code, update the comment.


7. Docstrings#

A docstring is a string literal placed as the first statement in a function, class, or module. It documents what that piece of code does. Use triple double quotes (""").

For simple functions, a single line is enough:

def square(x):
    """Return the square of x."""
    return x * x

For anything more involved, use a short summary line, a blank line, then details:

def compute_speed(distance, time):
    """Return the average speed for a trip.

    Parameters:
        distance: distance traveled in meters
        time: time elapsed in seconds (must be greater than 0)

    Returns:
        The average speed in meters per second.
    """
    return distance / time

Docstring conventions

  • The first line is a short summary, written as a command: “Return the square,” not “Returns the square.”

  • Put the closing """ on its own line for multi-line docstrings.

  • Write a docstring for every function you submit in this course, even simple ones.


8. Imports#

Imports go at the top of the file, after any module docstring and before any code.

One import per line, and group them in this order with a blank line between groups:

  1. Standard library imports (math, os, random)

  2. Third-party imports (numpy, matplotlib, pandas)

  3. Your own modules

# Good
import math
import os

import matplotlib.pyplot as plt
import numpy as np

import my_helpers
# Bad
import math, os, numpy as np      # multiple imports on one line
from math import *                # wildcard import; hides where names come from

Avoid from module import *. When you use a function like sqrt(x), a reader can’t tell whether it came from math, numpy, or somewhere else. Write math.sqrt(x) or from math import sqrt instead.


9. Common Pitfalls and Recommendations#

These small habits make your code more “Pythonic” and prevent real bugs.

Compare to None with is, not ==

# Good
if result is None:
    print("No result yet")

# Bad
if result == None:
    print("No result yet")

Don’t compare booleans to True or False

# Good
if is_valid:
    process(data)

# Bad
if is_valid == True:
    process(data)

Use the truthiness of empty sequences

# Good
if not items:
    print("The list is empty")

# Less clear
if len(items) == 0:
    print("The list is empty")

Be specific when catching exceptions

# Good
try:
    value = int(text)
except ValueError:
    print("Please enter a whole number.")

# Bad: silently catches every error, including typos in your own code
try:
    value = int(text)
except:
    print("Something went wrong.")

Be consistent with return. If some paths in a function return a value, every path should return something explicit, even if it’s None.

Use one statement per line. Don’t cram multiple statements onto one line with semicolons.

# Good
x = 1
y = 2

# Bad
x = 1; y = 2

10. Let Tools Help You#

You don’t have to memorize everything. Use software to check and fix your style.

Tool

What it does

Editor settings

Turn on “insert spaces for tabs,” “trim trailing whitespace,” and a visible ruler at column 79.

flake8

A linter: reports style violations and common errors.

ruff

A fast linter that checks many of the same things (and can auto-fix some).

black

An auto-formatter: rewrites your code into a consistent style. It uses 88 characters instead of 79 by default, so check which limit your course expects.

Try running flake8 your_script.py before you submit an assignment. Each message includes a line number and a code (like E501 line too long) that tells you what to fix.


Before-and-After Example#

Here is a complete function written poorly, then cleaned up.

Before

import math,os
def CalcArea(R,H = None):
  if H == None:
      return math.pi*R**2
  else :
      return 2*math.pi*R*(R+H)

After

import math


def calculate_area(radius, height=None):
    """Return the area of a circle, or the surface area of a cylinder.

    If height is None, return the area of a circle with the given radius.
    Otherwise, return the total surface area of a cylinder.
    """
    if height is None:
        return math.pi * radius ** 2
    else:
        return 2 * math.pi * radius * (radius + height)

What changed?

  1. Removed the unused os import and gave each import its own line.

  2. Added two blank lines before the function.

  3. Renamed CalcArea to calculate_area, and R and H to radius and height.

  4. Removed spaces around = in the default argument.

  5. Changed == None to is None.

  6. Fixed the 2-space and 6-space indentation to 4 spaces.

  7. Added spaces around operators and removed the space before the colon after else.

  8. Added a docstring.