Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: PEP 8 Style Guide

Python PEP 8 Style Guide - Complete Guide

Write clean, readable, and professional Python code.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is PEP 8?
  • Why Follow PEP 8?
  • Indentation
  • Line Length
  • Naming Conventions
  • Whitespace
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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?

1

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

2

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

3

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

4

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

5

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

6

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.

Loading Pyodide... 0%
Python Code Editor
==================================================
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:

1. How many spaces should you use for indentation?
2. What is the recommended maximum line length?
3. What naming convention should you use for variables?
4. Should you put spaces around arithmetic operators?
5. What naming convention should you use for constants?

Frequently Asked Questions

What is PEP 8? ▼

PEP 8 is Python's official style guide. It provides conventions for writing clean, readable, and consistent Python code. It covers indentation, naming, line length, whitespace, and more.

Do I have to follow PEP 8? ▼

No, PEP 8 is a guide, not a requirement. But following it makes your code more readable, consistent, and professional. Many open-source projects require PEP 8 compliance.

What tools can check PEP 8 compliance? ▼

Popular tools include: pylint, flake8, black (auto-formatter), autopep8, and pycodestyle. Many code editors also have built-in PEP 8 checkers.

What's the difference between PEP 8 and code formatting? ▼

PEP 8 is the style guide that defines how Python code should look. Code formatting tools (like black) automatically apply PEP 8 rules to your code.

Why is 79 characters the recommended line length? ▼

The 79-character limit comes from the days of 80-column terminals. It ensures code is readable on smaller screens, in side-by-side comparisons, and when printed. Many teams now use 100 characters for readability.

Can I use tabs instead of spaces? ▼

PEP 8 explicitly recommends using spaces, not tabs. Most code editors can be configured to insert spaces when you press the Tab key. This ensures consistent indentation across all editors.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: Testing Assignments Next: Docstrings →