Python Basics — PEP 8 Style Guide

3 minute read

PEP 8 Style Guide

PEP 8 is the official style guide for Python code. PEP stands for Python Enhancement Proposal, and PEP 8 specifically covers coding conventions to make Python code consistent and readable.

“Code is read much more often than it is written.” — Guido van Rossum

Why PEP 8 Matters

  • Makes your code readable to other developers
  • Creates a consistent look across Python projects
  • Helps prevent bugs caused by confusing formatting
  • Expected knowledge for job interviews and open-source contributions

Naming Conventions

Type Convention Example
Variables snake_case user_name, total_count
Functions snake_case calculate_total(), get_user()
Classes PascalCase UserProfile, ShoppingCart
Constants UPPER_SNAKE_CASE MAX_SIZE, API_KEY
Modules snake_case my_module.py, data_utils.py
Packages lowercase (no underscores) mypackage, utilities
Private _leading_underscore _internal_helper()
“Dunder” __double_underscore__ __init__(), __str__()

Indentation

Use 4 spaces per indentation level. Never mix tabs and spaces.

# ✅ Correct — 4 spaces
def greet(name):
    if name:
        print(f"Hello, {name}!")

# ❌ Wrong — 2 spaces
def greet(name):
  if name:
    print(f"Hello, {name}!")

Line Length

  • Maximum 79 characters for code
  • Maximum 72 characters for comments and docstrings
  • Use parentheses for line continuation:
# ✅ Correct — implicit line continuation inside parentheses
total = (first_variable
         + second_variable
         - third_variable)

# ✅ Also correct — backslash continuation
total = first_variable \
        + second_variable \
        - third_variable

Blank Lines

  • 2 blank lines before and after top-level function/class definitions
  • 1 blank line between methods inside a class
  • Use blank lines sparingly inside functions to separate logical sections
import os


def first_function():
    pass


def second_function():
    pass


class MyClass:

    def method_one(self):
        pass

    def method_two(self):
        pass

Imports

Imports should be at the top of the file, each on a separate line, organized in this order:

  1. Standard library imports
  2. Third-party imports
  3. Local/project imports

Separate each group with a blank line.

# ✅ Correct
import os
import sys

import requests
import numpy as np

from my_project import utils
from my_project.models import User
# ❌ Wrong — multiple imports on one line
import os, sys, json

Whitespace Rules

Around operators:

# ✅ Correct
x = 5
y = x + 3
result = x * y

# ❌ Wrong
x=5
y =x +3

Inside brackets — NO extra spaces:

# ✅ Correct
my_list = [1, 2, 3]
my_dict = {"key": "value"}
print(my_list[0])

# ❌ Wrong
my_list = [ 1, 2, 3 ]
my_dict = { "key": "value" }
print( my_list[ 0 ] )

After commas:

# ✅ Correct
def my_func(a, b, c):
    pass

# ❌ Wrong
def my_func(a,b,c):
    pass

Comments

# ✅ Good — explains WHY, not WHAT
# Calculate discount for loyalty members (10% after 1 year)
discount = total * 0.10

# ❌ Bad — states the obvious
# Multiply total by 0.10
discount = total * 0.10

Inline comments (use sparingly):

x = x + 1  # Compensate for border offset

Before & After Examples

Example 1 — Variable Naming

# ❌ Before (bad names)
x = "Alice"
y = 30
z = True

# ✅ After (descriptive names)
user_name = "Alice"
user_age = 30
is_active = True

Example 2 — Function Formatting

# ❌ Before (messy)
def calc(a,b,op):
    if op=='+':return a+b
    elif op=='-':return a-b

# ✅ After (PEP 8 compliant)
def calculate(a, b, operation):
    if operation == '+':
        return a + b
    elif operation == '-':
        return a - b

Example 3 — Import Organization

# ❌ Before
from my_app import helpers
import json
import requests
import os

# ✅ After
import json
import os

import requests

from my_app import helpers

Linting Tools

These tools automatically check (and sometimes fix) PEP 8 violations:

Tool What It Does Install
flake8 Checks PEP 8 + common errors pip install flake8
black Auto-formats code (opinionated) pip install black
autopep8 Auto-fixes PEP 8 violations pip install autopep8
pylint Deep code analysis + PEP 8 pip install pylint
isort Sorts imports automatically pip install isort

Using flake8

# Check a single file
flake8 my_script.py

# Check all Python files in a directory
flake8 my_project/

Using black

# Auto-format a file
black my_script.py

# Preview changes without applying
black --diff my_script.py

Quick Reference Card

Rule Standard
Indentation 4 spaces
Max line length 79 characters
Blank lines (top-level) 2
Blank lines (methods) 1
Naming (variables/functions) snake_case
Naming (classes) PascalCase
Naming (constants) UPPER_CASE
Imports Top of file, grouped
Trailing whitespace Remove it
File encoding UTF-8
String quotes Consistent (single or double)

Summary

  • PEP 8 is the official Python style guide — follow it
  • Use 4 spaces for indentation, never tabs
  • Keep lines under 79 characters
  • Use snake_case for variables/functions, PascalCase for classes
  • Organize imports at the top of the file in three groups
  • Add meaningful comments that explain why, not what
  • Use tools like flake8 and black to automate style checking
  • Consistent style makes code easier to read, review, and maintain

Next up: Practice Exercises →

Updated: