PEP 8

A beginner-friendly guide to PEP 8, the official Python style guide for writing clean and readable code.

Loading...
PEP 8

So far, we’ve learned how to write Python code using variables, functions, loops, and more. But writing code that works is only part of the job. It’s also important to make your code easy to read.

That’s where PEP 8 comes in.

What Is PEP 8?

PEP 8 is Python’s official style guide. It provides recommendations for formatting and organizing Python code so it’s easier to read and maintain.

Following these guidelines helps you:

  • Write readable code: Make your code easier to understand.
  • Stay consistent: Follow common conventions across your projects.
  • Work with others: Make your code easier for other developers to read and contribute to.

You don’t need to memorize every rule. Let’s start with some of the most useful ones.

1. Indentation

Remember how we used indentation inside functions, loops, and conditional statements?

PEP 8 recommends using 4 spaces per indentation level.

For example:

def greet():
    for i in range(3):
        print("Hello!")

Notice how each nested block is indented by four additional spaces.

Avoid mixing tabs and spaces for indentation. Consistent indentation makes the structure of your code easier to see.

2. Line Length

PEP 8 recommends keeping lines of code to 79 characters or fewer. For comments and docstrings, the recommended limit is generally 72 characters.

If a line is too long, you can split it across multiple lines.

For example:

# Instead of writing everything on one long line:
message = (
    "Welcome to the Python from Scratch series! "
    "Let's keep learning."
)
 
print(message)

The parentheses let Python treat the strings as one expression across multiple lines.

You don’t have to count every character manually, but try to avoid unnecessarily long lines.

3. Blank Lines

Blank lines help separate different parts of your code and make it easier to scan.

PEP 8 recommends:

  • Two blank lines between top-level function and class definitions.
  • One blank line between methods inside a class.

For example:

def greet():
    print("Hello!")
 
 
def say_goodbye():
    print("Goodbye!")

The blank lines make it easier to see where one function ends and the next begins.

4. Imports

PEP 8 recommends placing imports at the top of your file, usually before the rest of your code.

When you have different types of imports, group them in this order:

  1. Standard library imports.
  2. Third-party imports.
  3. Imports from your own project.

For example:

import math
import random
 
import numpy as np
 
from myproject import mymodule

Here, math and random belong to Python’s standard library, numpy is a third-party package, and mymodule belongs to the project.

Keep a blank line between these groups to make them easier to distinguish.

5. Whitespace

PEP 8 recommends using spaces consistently around operators and punctuation.

For example:

# Correct
x = 1 + 2
y = (a, b)
 
# Incorrect
x = 1  + 2
y = ( a, b )

Notice the differences:

  • Use a single space around operators such as =, +, and -.
  • Don’t add unnecessary spaces just inside parentheses.
  • Avoid extra spaces that make expressions harder to read.
  • These small changes make your code look cleaner.

6. Naming Conventions

We already learned Python’s variable naming rules. PEP 8 provides additional conventions for naming variables, functions, classes, and constants.

Here are the main ones:

What you’re naming Recommended style Example
Variables snake_case user_name
Functions snake_case calculate_total()
Classes PascalCase StudentProfile
Constants UPPER_CASE MAX_RETRIES

Here’s an example:

MAX_RETRIES = 3
 
 
class StudentProfile:
    def show_details(self):
        student_name = "Shefali"
        print(student_name)

Notice how each name follows a different convention.

Using consistent naming makes it easier to understand what each part of your code represents.

7. Comments and Docstrings

In the previous two lessons, we learned about comments and docstrings.

PEP 8 recommends writing comments that are clear, relevant, and easy to understand. Docstrings should also follow consistent formatting conventions.

For example:

def square(number):
    """Return the square of a number."""
    return number ** 2

The docstring briefly explains what the function does.

Avoid comments that simply repeat the code without adding useful information.

For example, this comment isn’t particularly helpful:

# Add 1 to x
x = x + 1

The code already makes that clear. A comment is more useful when it explains why something is being done, especially when the reason isn’t obvious.

Why Does PEP 8 Matter?

Imagine reading a project where every function uses different indentation, variables have inconsistent names, and code is packed into long lines.

Even if the program works, understanding it can be difficult.

PEP 8 gives Python developers a common set of style recommendations, making code easier to read and maintain.

You can also use tools such as Ruff or pycodestyle to check your code against style rules.

You don’t need to start using these tools right away. For now, focus on applying the basic guidelines as you write your programs.


👉 Next tutorial: The Zen of Python