← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 1 of 15

Python PEP 8 Style Guide

What is PEP 8?

PEP 8 is Python's official style guide, and following it isn't about rigid rule-following for its own sake -- it exists so that any Python developer can read unfamiliar code without first having to learn that particular author's personal formatting habits.

Example: What is PEP 8?

python
# PEP 8 is Python's official style guide
def calculate_total(price, quantity):
    return price * quantity

print(calculate_total(10, 3))

Naming Conventions

PEP 8 recommends snake_case for variables and functions, PascalCase for class names, and UPPER_SNAKE_CASE for constants. Consistent naming lets a reader infer what kind of thing an identifier refers to purely from how it's capitalized, before even reading its definition.

Example: Naming Conventions

python
user_count = 5           # snake_case for variables
MAX_RETRIES = 3           # UPPER_SNAKE_CASE for constants

class UserAccount:        # PascalCase for classes
    pass

print(user_count, MAX_RETRIES)

Whitespace and Spacing

PEP 8 discourages extra whitespace directly inside brackets or parentheses (foo( x ) instead of foo(x)) and directly before commas or colons, since inconsistent spacing makes code visually noisier without adding any actual clarity.

Example: Whitespace and Spacing

python
def foo(x):
    return x

print(foo(5))  # no extra space inside parentheses

Blank Lines

Top-level function and class definitions should be separated by exactly two blank lines, while methods within a class are separated by a single blank line. This consistent vertical spacing helps a reader's eye quickly distinguish where one definition ends and the next begins.

Example: Blank Lines

python
def first_function():
    pass


def second_function():
    pass


print("Two blank lines separate top-level functions")

Style with Imports

Imports belong at the very top of a file, grouped in a specific order: standard library imports first, then third-party packages, then your own local modules -- with a blank line separating each group. This ordering makes a file's external dependencies obvious at a glance.

Example: Style with Imports

python
import math          # standard library

# import requests    # third-party would go next

print(math.pi)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.