Velamuvi AIAcademy

Lesson 16 of 16 · Project Setup

Writing Readable Code With PEP 8

Learn the PEP 8 style guide for Python: naming, spacing, line length, imports, comparisons and docstrings, plus the tools that format your code automatically.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What PEP 8 is and why style matters
  • How to name variables, functions, classes and constants
  • The spacing, line length and import rules most teams follow
  • How tools can format your code for you

Code is read more than it is written

You write a line of code once, but you and others read it many times: when fixing a bug, adding a feature or reviewing a colleague's work. Code that is easy to read saves hours.

PEP 8 is Python's official style guide. A PEP is a "Python Enhancement Proposal", a design document for Python, and number 8 describes how Python code should look. Almost every Python team follows it, so following it yourself makes your code feel familiar to everyone.

Python itself has a small poem about this. Run it:

Try it yourselfPython
import this

Naming

Names are the most important part of readable code. PEP 8 uses a different style for each kind of name.

Kind of nameStyleExample
Variables and functionssnake_casetotal_price, load_data()
ConstantsUPPER_CASEMAX_RETRIES = 3
ClassesPascalCaseChatClient
Modules and packagesshort, lowercaseutils.py, weather

Beyond the style, choose names that say what something is.

# Hard to understand
def calc(l):
    t = 0
    for x in l:
        t += x
    return t / len(l)

# Clear
def average(scores):
    total = 0
    for score in scores:
        total += score
    return total / len(scores)

Avoid single letters except for very short loops, and never use l (lowercase L), O or I on their own, because they look like the numbers 1 and 0.

Spacing

  • Indent with 4 spaces, never tabs.
  • Put one space around = and operators: total = price * quantity.
  • No spaces around = in keyword arguments and defaults: round(value, ndigits=2), def greet(name="Ada").
  • One space after a comma, none before: print(a, b, c).
  • Two blank lines between top-level functions, one blank line between logical sections inside a function.
# Cramped and inconsistent
def area(w,h):
  return w*h
def perimeter(w , h):
    return 2*(w+h)

# PEP 8
def area(width, height):
    return width * height


def perimeter(width, height):
    return 2 * (width + height)

Line length

PEP 8 recommends keeping lines to 79 characters. Many modern teams use a slightly longer limit, such as 88 or 100. Whatever the number, the point is the same: lines you can read without scrolling sideways. Break long lines inside brackets, which Python allows without any special symbols.

response = client.generate(
    prompt=prompt,
    temperature=0.2,
    max_tokens=500,
)

Imports

Put all imports at the top of the file, one per line, in three groups separated by a blank line:

import json  # 1. standard library
from pathlib import Path

import requests  # 2. installed packages

from weather.api import forecast  # 3. your own modules

Avoid from module import *. It hides where names come from and can overwrite your own variables.

Comparisons and conditions

A few small habits that Python programmers expect:

Try it yourselfPython
items = []
result = None

if not items:              # rather than: if len(items) == 0
    print("The list is empty")

if result is None:         # rather than: if result == None
    print("No result yet")

is_ready = True
if is_ready:               # rather than: if is_ready == True
    print("Ready")

Empty collections, 0, "" and None all count as false in an if, so you can test them directly. Compare with None using is.

Docstrings and comments

A docstring is a string right under a function's first line. It explains what the function does, and editors show it when you hover over the function.

Try it yourselfPython
def average(scores):
    """Return the mean of a list of scores, or 0.0 for an empty list."""
    if not scores:
        return 0.0
    return sum(scores) / len(scores)


print(average([80, 90, 100]))
print(average.__doc__)

Comments should explain why, not repeat what the code already says.

# Useless: says what the code already says
count = count + 1  # add one to count

# Useful: explains a decision
timeout = 30  # the API often takes 20 seconds under load

Let the tools do it

You do not have to remember every rule. Formatters rewrite your code into a consistent style automatically, and linters point out problems.

  • Ruff is a very fast linter and formatter that checks PEP 8 and much more.
  • Black is a popular formatter with almost no settings to argue about.

Install one in your environment, for example python -m pip install ruff, then run ruff format . to format a whole project and ruff check . to find problems. Most editors, including VS Code, can format your file every time you save it.

Common mistakes

Practice exercise

Rewrite a messy function so that it follows PEP 8 and handles an empty list.

Your solutionPython
# This works, but breaks almost every PEP 8 rule:
def CalcAvg(L):
  return sum(L)/len(L)

# Write a new function called calculate_average(scores) that:
# - follows PEP 8 (snake_case, 4-space indent, spaces around operators)
# - has a one-line docstring
# - returns 0.0 for an empty list instead of crashing


print(calculate_average([90, 80, 70]))
print(calculate_average([]))

# Output must be exactly:
# 80.0
# 0.0
Knowledge check

Which name follows PEP 8 for a constant?

Summary

  • PEP 8 is Python's style guide, followed by almost every Python team.
  • snake_case for variables and functions, UPPER_CASE for constants and PascalCase for classes.
  • 4-space indents, spaces around operators, short lines and imports grouped at the top.
  • Test emptiness with if not items, compare with is None, and explain functions with docstrings.
  • Let a formatter such as Ruff or Black keep your code consistent.

You have finished Python Intermediate

You can now write Pythonic code with comprehensions, unpacking and slicing, use the full power of functions, work with JSON, CSV files and dates, and set up a project with a virtual environment, packages and a clean structure.

Where next?

Finished reading? Tick it off to track your progress.