- What is PEP 8 — Python's official style guide
- Why follow it — read better code, work better with others
- Indentation — 4 spaces, not tabs
- Line length — keep lines under 79 characters
- Naming conventions — variables, functions, classes
- Whitespace — spaces around operators
What is PEP 8?
PEP 8 stands for Python Enhancement Proposal 8. It's the official style guide for Python code. It tells you how to format your code so that it's consistent, readable, and professional.
Think of PEP 8 like a house style guide for writing. Just like newspapers have style guides for consistency, Python has PEP 8 so that all Python code looks similar and is easy to read.
Following PEP 8 makes your code easier to read, easier to maintain, and easier to share with others. It's not required, but it's highly recommended.
💡 Key concept: PEP 8 is a set of guidelines for writing Python code that is consistent, readable, and professional.
Why Follow PEP 8?
The Benefits of Following PEP 8
Following PEP 8 makes your code better in many ways. Let's see the difference.
# Why Follow PEP 8?
print("=" * 50)
print("WHY FOLLOW PEP 8?")
print("=" * 50)
# ============================================================
# WITHOUT PEP 8 - Hard to Read
# ============================================================
print("\n1. WITHOUT PEP 8")
print("""
def calculate_total(items,prices):
total=0
for i in range(len(items)):
total+=prices[i]
if total>100:
print("Total over 100")
return total
# Problems:
# - Inconsistent spacing
# - Hard to read
# - No blank lines
# - Hard to maintain
""")
# ============================================================
# WITH PEP 8 - Clean and Readable
# ============================================================
print("\n2. WITH PEP 8")
print("""
def calculate_total(items, prices):
\"\"\"Calculate the total price of all items.\"\"\"
total = 0
for i in range(len(items)):
total += prices[i]
if total > 100:
print("Total over 100")
return total
# Benefits:
# - Consistent spacing
# - Easy to read
# - Clear structure
# - Easy to maintain
""")
# ============================================================
# BENEFITS SUMMARY
# ============================================================
print("\n" + "-" * 30)
print("BENEFITS OF PEP 8")
print("-" * 30)
print("""
- Code is easier to read
- Code is easier to maintain
- Consistent with other Python code
- Easier to collaborate with others
- Professional appearance
- Fewer bugs (easier to spot mistakes)
- Tools like linters work better
""")
Benefits of PEP 8:
- Readability — clean code is easier to understand
- Maintainability — easier to fix and update
- Consistency — looks like other Python code
- Collaboration — easier to work with others
- Professional — shows attention to quality
Quick Check: What is PEP 8? (Answer: Python's official style guide for writing clean, readable code)
Indentation
Use 4 Spaces, Not Tabs
PEP 8 says to use 4 spaces for indentation. Never use tabs. Most code editors can convert tabs to spaces automatically.
# Indentation - 4 Spaces
print("=" * 50)
print("INDENTATION")
print("=" * 50)
# ============================================================
# GOOD - 4 Spaces Indentation
# ============================================================
print("\n1. GOOD - 4 Spaces")
print("""
def calculate_average(numbers):
\"\"\"Calculate the average of a list of numbers.\"\"\"
if not numbers:
return 0
total = 0
for num in numbers:
total += num
return total / len(numbers)
# Each indent is 4 spaces
# Consistent and readable
""")
# ============================================================
# BAD - Tabs or Inconsistent Indentation
# ============================================================
print("\n2. BAD - Tabs or Inconsistent")
print("""
def calculate_average(numbers):
\"\"\"Calculate the average\"\"\"
if not numbers:
return 0
total = 0
for num in numbers:
total += num
return total / len(numbers)
# Problems:
# - Uses tabs (not spaces)
# - Inconsistent with other Python code
# - Looks different in different editors
""")
# ============================================================
# INDENTATION RULES
# ============================================================
print("\n3. INDENTATION RULES")
print("""
┌─────────────────────────────────────────────────────────────────────┐
│ RULES │
├─────────────────────────────────────────────────────────────────────┤
│ 1. Use 4 spaces per indentation level │
│ 2. Never use tabs (most editors can convert tabs to spaces) │
│ 3. Indent after colons (if, for, while, def, class) │
│ 4. Use a new indent level for blocks │
│ 5. Keep indentation consistent throughout the file │
└─────────────────────────────────────────────────────────────────────┘
Example:
if condition: # Colon, start new indent
do_something() # Indented 4 spaces
if other: # Nested, indent another 4 spaces
do_more() # Indented 8 spaces
def function(): # Colon, start new indent
return "Hello" # Indented 4 spaces
""")
Indentation key points:
- 4 spaces — the standard indentation
- No tabs — use spaces only
- Consistent — same indentation throughout
- After colons — indent after if, for, def, class
Quick Check: How many spaces should you use for indentation? (Answer: 4 spaces)
Line Length
Keep Lines Under 79 Characters
PEP 8 recommends keeping lines to a maximum of 79 characters. This makes your code readable on smaller screens and side-by-side comparisons.
# Line Length
print("=" * 50)
print("LINE LENGTH")
print("=" * 50)
# ============================================================
# GOOD - Lines Under 79 Characters
# ============================================================
print("\n1. GOOD - Under 79 Characters")
print("""
def process_user_data(username, email, age, city):
\"\"\"Process and validate user data.\"\"\"
if not username:
raise ValueError("Username is required")
if not email or '@' not in email:
raise ValueError("Invalid email address")
if age < 0 or age > 150:
raise ValueError("Invalid age")
return {"username": username, "email": email, "age": age, "city": city}
# All lines are under 79 characters
# Easy to read on any screen
""")
# ============================================================
# BAD - Lines Over 79 Characters
# ============================================================
print("\n2. BAD - Over 79 Characters")
print("""
def process_user_data(username, email, age, city):
if not username:
raise ValueError("Username is required")
if not email or '@' not in email:
raise ValueError("Invalid email address")
if age < 0 or age > 150:
raise ValueError("Invalid age")
return {"username": username, "email": email, "age": age, "city": city}
# Some lines are over 79 characters
# Harder to read on smaller screens
""")
# ============================================================
# BREAKING LONG LINES
# ============================================================
print("\n3. BREAKING LONG LINES")
print("""
# Breaking long lines with parentheses
result = calculate_very_long_function_name(
argument1, argument2, argument3,
argument4, argument5
)
# Breaking strings with implicit concatenation
message = (
"This is a very long message that would "
"be over 79 characters if written on one line"
)
# Breaking lists
items = [
"item1", "item2", "item3",
"item4", "item5", "item6"
]
""")
# ============================================================
# LINE LENGTH SUMMARY
# ============================================================
print("\n4. LINE LENGTH SUMMARY")
print("""
┌─────────────────────────────────────────────────────────────────────┐
│ LINE LENGTH GUIDELINES │
├─────────────────────────────────────────────────────────────────────┤
│ • Maximum: 79 characters │
│ • For comments/docstrings: 72 characters │
│ • Use parentheses to break long lines │
│ • Use backslashes sparingly │
│ • Break at logical points (after commas, operators) │
│ • Some teams allow 100 characters for readability │
└─────────────────────────────────────────────────────────────────────┘
""")
Line length key points:
- 79 characters — maximum line length
- 72 for comments — docstrings and comments
- Use parentheses — to break long lines
- Break logically — at commas, operators
Quick Check: What is the recommended maximum line length? (Answer: 79 characters)
Naming Conventions
How to Name Things
PEP 8 has specific naming conventions for different types of variables, functions, classes, and more.
# Naming Conventions
print("=" * 50)
print("NAMING CONVENTIONS")
print("=" * 50)
# ============================================================
# GOOD NAMES
# ============================================================
print("\n1. GOOD NAMES")
print("""
# Variables and functions: snake_case
user_name = "Alice"
user_age = 30
def calculate_total():
pass
# Constants: UPPER_CASE
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
# Classes: CamelCase
class UserProfile:
pass
class DatabaseConnection:
pass
# Private variables: _leading_underscore
_private_var = "secret"
def _internal_method():
pass
# Names should be descriptive
# Avoid single-letter names (except for loops)
""")
# ============================================================
# BAD NAMES
# ============================================================
print("\n2. BAD NAMES")
print("""
# Bad - too short or unclear
u = "Alice" # What is 'u'?
age = 30 # What is this for?
def calc(): # Calculate what?
pass
# Bad - inconsistent
userName = "Alice" # CamelCase for variable
user_age = 30 # snake_case for variable
# Bad - too generic
data = get_data()
temp = process(temp)
# Bad - using reserved words
class = "math" # 'class' is a reserved word
import = "sys" # 'import' is a reserved word
""")
# ============================================================
# NAMING CONVENTIONS SUMMARY
# ============================================================
print("\n3. NAMING CONVENTIONS SUMMARY")
print("""
┌─────────────────────────────┬─────────────────────────────────────────────┐
│ Type │ Convention │
├─────────────────────────────┼─────────────────────────────────────────────┤
│ Variables │ snake_case (lowercase with underscores) │
│ Functions │ snake_case │
│ Classes │ CamelCase (Capitalized words) │
│ Constants │ UPPER_CASE (all caps with underscores) │
│ Private variables/methods │ _leading_underscore │
│ Private (name mangling) │ __double_leading_underscore │
│ Modules │ lowercase_with_underscores │
│ Packages │ lowercase (no underscores) │
Examples:
# Good
user_name = "Alice"
def get_user_data():
pass
class UserProfile:
pass
MAX_CONNECTIONS = 10
_internal_var = 42
# Bad
USERNAME = "Alice" # Should be lowercase
def GetUserData(): # Should be snake_case
pass
class user_profile: # Should be CamelCase
pass
""")
Naming conventions key points:
- snake_case — variables, functions
- CamelCase — classes
- UPPER_CASE — constants
- _leading_underscore — private
- Be descriptive — names should explain purpose
Quick Check: What naming convention should you use for a class? (Answer: CamelCase)
Whitespace
Spaces Around Operators
PEP 8 says to use spaces around operators and after commas. This makes your code more readable.
# Whitespace
print("=" * 50)
print("WHITESPACE")
print("=" * 50)
# ============================================================
# GOOD - Spaces Around Operators
# ============================================================
print("\n1. GOOD - Spaces Around Operators")
print("""
# Arithmetic operators
result = a + b * c
total = price * quantity
# Assignment operators
x = 5
y = x + 3
# Comparison operators
if x > 10:
pass
# After commas
items = [1, 2, 3, 4, 5]
function_call(arg1, arg2, arg3)
# After colons in dictionaries
user = {"name": "Alice", "age": 30}
# In function definitions
def function(arg1, arg2, arg3=10):
pass
""")
# ============================================================
# BAD - No Spaces or Inconsistent
# ============================================================
print("\n2. BAD - No Spaces")
print("""
# Bad - no spaces
result=a+b*c
total=price*quantity
# Bad - no space after comma
items=[1,2,3,4,5]
function_call(arg1,arg2,arg3)
# Bad - no space around assignment
x=5
y=x+3
# Bad - no space after colon in dict
user={"name":"Alice","age":30}
""")
# ============================================================
# SPACING RULES
# ============================================================
print("\n3. SPACING RULES")
print("""
┌─────────────────────────────────────────────────────────────────────┐
│ RULES │
├─────────────────────────────────────────────────────────────────────┤
│ 1. Use spaces around arithmetic operators: a + b * c │
│ 2. Use spaces around assignment: x = 5 │
│ 3. Use spaces after commas: [1, 2, 3] │
│ 4. Use spaces after colons in dicts: {"key": "value"} │
│ 5. No space before colons: if x > 5: │
│ 6. No space before commas: function(arg1, arg2) │
│ 7. No spaces inside parentheses: function(arg) │
│ 8. No spaces inside brackets: list[0] │
└─────────────────────────────────────────────────────────────────────┘
Common exceptions:
# Function arguments with defaults
def func(arg1, arg2=10): # No space around = in defaults
# Keyword arguments
func(arg1=10, arg2=20) # No space around = in kwargs
""")
Whitespace key points:
- Spaces around operators —
a + b - Spaces after commas —
[1, 2, 3] - No space before colon —
if x > 5: - No spaces inside parentheses —
func(arg)
Quick Check: Should you put spaces around arithmetic operators? (Answer: Yes, a + b not a+b)
More Best Practices
Additional PEP 8 Guidelines
# More PEP 8 Best Practices
print("=" * 60)
print("MORE PEP 8 BEST PRACTICES")
print("=" * 60)
# ============================================================
# 1. BLANK LINES
# ============================================================
print("\n1. BLANK LINES")
print("""
# Good - use blank lines to separate sections
def function_one():
pass
def function_two():
pass
class MyClass:
def method_one(self):
pass
def method_two(self):
pass
# Bad - no blank lines
def function_one():
pass
def function_two():
pass
class MyClass:
def method_one(self):
pass
def method_two(self):
pass
""")
# ============================================================
# 2. IMPORTS
# ============================================================
print("\n2. IMPORTS")
print("""
# Good - imports on separate lines
import os
import sys
from datetime import datetime
# Good - grouped imports
import os
import sys
import json
from datetime import datetime
from collections import defaultdict
# Bad - multiple imports on one line
import os, sys, json
# Bad - imports mixed with code
import os
x = 5
import sys # Imports should be at the top
""")
# ============================================================
# 3. COMMENTS
# ============================================================
print("\n3. COMMENTS")
print("""
# Good - clear comments explaining why
# Check if user is authorized to access this resource
if user.has_permission("read"):
return data
# Bad - obvious comments
# Add 1 to x
x = x + 1
# Bad - outdated comments
# Calculate total price (no longer does this)
return quantity * price + tax
""")
# ============================================================
# 4. DOCSTRINGS
# ============================================================
print("\n4. DOCSTRINGS")
print("""
# Good - docstrings for functions and classes
def add_numbers(a, b):
\"\"\"Add two numbers and return the result.
Args:
a (int): First number
b (int): Second number
Returns:
int: The sum of a and b
\"\"\"
return a + b
# Good - one-line docstring for simple functions
def double(x):
\"\"\"Return twice the input value.\"\"\"
return x * 2
""")
# ============================================================
# 5. AVOID EXTRA PARENTHESES
# ============================================================
print("\n5. AVOID EXTRA PARENTHESES")
print("""
# Good - clean
if x > 5:
pass
# Bad - extra parentheses
if (x > 5):
pass
# Good - clean
result = a + b * c
# Bad - unnecessary parentheses
result = a + (b * c)
""")
More best practices key points:
- Blank lines — separate functions and classes
- Imports — one per line, grouped at top
- Comments — explain why, not what
- Docstrings — document functions and classes
- No extra parentheses — keep code clean
Quick Check: Where should import statements be placed? (Answer: At the top of the file)
Try It Yourself
See the difference between good and bad style in the editor below.
PEP 8 - PRACTICE
==================================================
1. BAD STYLE
Total over 100
60
2. GOOD STYLE
Total over 100
60
You've Got It!
You now understand PEP 8 style guide. You know how to write clean, readable, and professional Python code.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is PEP 8?
Do I have to follow PEP 8?
What tools can check PEP 8 compliance?
What's the difference between PEP 8 and code formatting?
Why is 79 characters the recommended line length?
Can I use tabs instead of spaces?
Where to Go From Here
Now that you understand PEP 8, check out these related topics:
Docstrings
Learn how to document your code properly.
Learn More →Logging
Learn about proper logging practices.
Learn More →Code Optimization
Learn how to write efficient Python code.
Learn More →