Writing Pythonic CodeBeginner7 min58 / 63

PEP 8 & Style

Learn Python's official style guide, PEP 8, and discover how clean, consistent code makes you a better teammate and a better programmer.

Imagine two restaurants. One has a clean kitchen where every knife has its place, every label is readable, and the prep cook always knows where to find things. The other has pots everywhere, handwritten labels no one can read, and chaos at rush hour. Both produce food — but only one runs smoothly.

Code works the same way. Python gives you a lot of freedom in how you write it, but the Python community agreed on a shared rulebook called PEP 8. When everyone follows the same style, code becomes much easier to read, debug, and share.

See it in action

Visual walkthrough1 / 6
1

Python Has a Style Rulebook

PEP 8 is Python's official style guide — a shared set of rules so every Python developer's code looks familiar. Think of it as the grammar handbook for the Python language.

PEP stands for Python Enhancement Proposal. PEP 8 (from 2001) is the one that defines style.
Note

What is PEP 8?

PEP stands for Python Enhancement Proposal. PEP 8 is proposal number 8, written in 2001, and it defines the official style guide for Python code. It covers everything from indentation to naming to blank lines.

#Indentation: Use 4 Spaces

Python uses indentation to define blocks of code (like the body of a function or loop). PEP 8 says: always use 4 spaces per level. Never use tabs, and never use 2 spaces — consistency is everything.

Stick to 4 spaces — your future self will thank you.
# Good: 4 spaces per level
def greet(name):
    message = "Hello, " + name
    print(message)

# Bad: 2 spaces (avoid)
def greet_bad(name):
  message = "Hello, " + name
  print(message)
Common mistake

Tabs vs. Spaces

Mixing tabs and spaces in the same file causes a TabError in Python 3. Most code editors can be set to insert 4 spaces when you press Tab — turn that on and you never have to think about it again.

#Naming Conventions

PEP 8 has clear rules for naming things. Different kinds of names use different styles:

  • Variables and functionssnake_case (all lowercase, words joined by underscores)
  • ClassesPascalCase (each word starts with a capital letter, no underscores)
  • ConstantsUPPER_CASE (all caps, words joined by underscores)
Each naming style signals what kind of thing you are looking at.
# Variables and functions: snake_case
user_name = "Alice"
max_score = 100

def calculate_total(price, tax_rate):
    return price * (1 + tax_rate)

# Classes: PascalCase
class ShoppingCart:
    pass

# Constants: UPPER_CASE
MAX_RETRIES = 3
PI = 3.14159
Think of it like

Naming is like signage

Think of naming styles like road signs. ALL CAPS means a constant warning (don't change this!), PascalCase is a proper noun (a named thing, like a class), and snake_case is everyday directions. You know what to expect before you even read the full name.

#Spaces Around Operators

PEP 8 says to put one space on each side of most operators. This gives your code room to breathe and makes it much easier to scan.

Spaces make math expressions readable at a glance.
# Good: spaces around operators
x = 5 + 3
result = x * 2 - 1
is_valid = x > 0 and x < 10

# Bad: cramped (avoid)
x=5+3
result=x*2-1
Tip

Exception: keyword arguments

When passing keyword arguments to a function, do not add spaces around the =. Write print(end="") not print(end = ""). This is one of PEP 8's few exceptions.

#Line Length and Blank Lines

PEP 8 originally recommended keeping lines under 79 characters. Many modern teams allow up to 99 characters. Either way, the goal is that you never have to scroll sideways to read code.

Blank lines also matter: - Use two blank lines before and after a top-level function or class definition. - Use one blank line between methods inside a class. - Use blank lines inside a function to separate logical steps.

Two blank lines separate top-level functions — this is the standard.
import math


def circle_area(radius):
    """Return the area of a circle."""
    return math.pi * radius ** 2


def circle_perimeter(radius):
    """Return the perimeter of a circle."""
    return 2 * math.pi * radius


area = circle_area(5)
print(area)

#Import Order

When you import modules, PEP 8 says to group them in this order, with a blank line between each group:

  1. Standard library imports (built into Python, e.g. math, os)
  2. Third-party imports (installed via pip, e.g. requests, pandas)
  3. Local imports (your own modules)
Grouping imports makes dependencies obvious at a glance.
# 1. Standard library
import math
import os

# 2. Third-party
import requests

# 3. Local modules
import my_utils

#Tools That Do the Work For You

You do not have to memorize every PEP 8 rule. The Python ecosystem has tools that check and even fix your code automatically:

  • `black` — an opinionated auto-formatter. Run it and your code is instantly PEP 8 compliant. Zero arguments needed.
  • `flake8` or `ruff` — linters that highlight style problems without changing your code, so you can learn from them.

Most professional teams run one of these tools automatically before every commit.

These commands run in your terminal, not inside a Python script.
# Install black (run this in your terminal, not in Python)
# pip install black

# Then format any file:
# black my_script.py

# Install ruff (a fast modern linter):
# pip install ruff

# Check a file for style issues:
# ruff check my_script.py
Tip

Set up your editor

VS Code, PyCharm, and most other editors can run black or ruff automatically every time you save a file. Search your editor's extensions for "Black Formatter" or "Ruff" and enable "format on save" — then style is never your problem again.

#Why Style Matters for Teams

When you code alone, style is a courtesy to your future self. When you work with a team, style is a necessity. A consistent codebase means:

  • New teammates can read the code without a guide
  • Code reviews focus on logic, not formatting debates
  • Git diffs are cleaner — one changed idea, not fifty reformatted lines
  • Bugs hide less easily in well-structured code

The Zen of Python (type import this in Python) says: Readability counts. PEP 8 is how Python lives that value.

Quick check

Which naming style does PEP 8 recommend for a Python function?

Key takeaways

  • PEP 8 is Python's official style guide — it covers indentation, naming, spacing, and more.
  • Use 4 spaces for indentation, snake_case for functions/variables, PascalCase for classes, and UPPER_CASE for constants.
  • Spaces around operators and blank lines between functions make code much easier to scan.
  • Tools like `black` (auto-formatter) and `ruff` or `flake8` (linters) enforce style automatically so you don't have to memorize every rule.
  • Consistent style is an act of kindness to your teammates — and to the future version of you.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
MAX_SPEED = 120

def calculate_distance(speed, hours):
    return speed * hours

result = calculate_distance(MAX_SPEED, 2)
print(result)
Fix the bug#2

This code has a PEP 8 style bug. What is wrong?

fix-bug
def calculateArea(width, height):
  return width * height

result = calculateArea(5, 3)
print(result)
Fill in the blank#3

Complete the constant name and variable name so both follow PEP 8 naming conventions. The code should print 314.159.

 = 3.14159

def circle_area():
    return PI * radius * radius

print(circle_area(10))
Reorder the lines#4

Put these import lines in the correct PEP 8 order (standard library first, then third-party, then local).

1
import math
2
 
3
import my_utils
4
import os
5
import requests
6
 
Your turn
Practice exercise

The code below has several PEP 8 violations: wrong indentation, bad naming, missing spaces, and mixed-up import order. Fix all the style issues so the code passes PEP 8.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable