01 / 20
PEP 8

PEP 8
Style Conventions

Master the official Python style guide that makes your code readable, consistent, and professional.

Python

What is PEP 8?

PEP 8 stands for Python Enhancement Proposal #8. It is the official style guide for writing Python code, authored by Guido van Rossum and other core developers. It defines conventions for formatting, naming, and organizing your Python programs.

Why Style Matters

Readability
Consistent formatting lets others (and future you) understand code quickly.
Collaboration
Teams agree on one style, reducing friction during code reviews.
Professionalism
Clean code signals competence in open-source projects and job applications.

The Big Picture of PEP 8

PEP 8 Indentation Naming Whitespace Imports Line Length Comments Six core areas of PEP 8 conventions

Indentation: 4 Spaces

PEP 8 requires 4 spaces per indentation level. Never mix tabs and spaces. Most editors can convert tabs to spaces automatically.

✓ Correct
def greet(name): # 4 spaces if name: print("Hello") print(name)
✕ Wrong
def greet(name): # 2 spaces if name: print("Hello") print(name)

Naming Conventions

Element Style Example
Variables, functions snake_case my_variable, calculate_sum
Classes PascalCase StudentRecord, HttpClient
Constants UPPER_SNAKE MAX_SIZE, PI_VALUE
Modules, packages snake_case my_module, utils
Private _leading_underscore _internal_helper

snake_case vs camelCase

✓ Python (PEP 8)
student_name = "Alice" total_score = 95 is_passing = True def calculate_average(): pass
✕ Not Pythonic
studentName = "Alice" totalScore = 95 isPassing = True def calculateAverage(): pass

Line Length: 79 Characters

PEP 8 recommends a maximum line length of 79 characters for code and 72 characters for comments and docstrings. This ensures readability across different editors and side-by-side windows.

# Too long: hard to read without scrolling result = first_value + second_value + third_value + fourth_value + fifth_value + sixth_value # Better: break with parentheses result = ( first_value + second_value + third_value + fourth_value + fifth_value + sixth_value )

Whitespace Rules

1
Around operators: One space on each side of assignment and comparison operators: x = 5, not x=5.
2
After commas: One space after commas in lists, arguments, and tuples: [1, 2, 3], not [1,2,3].
3
No space inside brackets: Write my_list[0], not my_list[ 0 ]. Write func(arg), not func( arg ).
4
No space before colons: Write if x:, not if x :. Write d = {"key": val}, not d = {"key" : val}.

Blank Lines and Spacing

import os import sys # 2 blank lines before top-level class MyClass: """A sample class.""" # 1 blank line between methods def __init__(self): self.value = 0 def increment(self): self.value += 1 def top_level_function(): pass
2 blank lines
Before and after top-level functions and class definitions.
1 blank line
Between method definitions inside a class.

Organizing Imports

PEP 8 requires imports at the top of the file, grouped in a specific order with a blank line between each group:

1
Standard library imports: os, sys, math, json.
2
Third-party imports: numpy, requests, flask.
3
Local/project imports: your own modules and packages.
import os import sys from pathlib import Path import numpy as np import requests from my_project import utils from my_project.models import User

Comments and Docstrings

# Block comment: explain the next section # Each line starts with # and a single space x = x + 1 # Inline comment: 2 spaces before # def calculate_area(radius): """Calculate the area of a circle. Args: radius: The radius of the circle. Returns: The area as a float. """ return 3.14159 * radius ** 2

How to Apply PEP 8

1
Configure your editor: Set tab size to 4 spaces, enable "format on save," and add a ruler at column 79.
2
Use a linter: Install flake8 or pylint to catch style violations automatically as you type.
3
Use an auto-formatter: Tools like black or autopep8 reformat your code instantly to match PEP 8.
4
Review before committing: Read your code aloud. If a name or structure confuses you, refactor it.
5
Be consistent: If a project uses a slightly different convention, follow the project's style over PEP 8.

Example: Fixing Bad Style

✕ Before
import sys,os def MyFunc( x,y ): Result=x+y return Result
✓ After
import os import sys def my_func(x, y): result = x + y return result

Example: Class Formatting

class StudentGrade: """Track a student's grades and compute average.""" MAX_GRADE = 100 def __init__(self, name): self.name = name self._grades = [] def add_grade(self, grade): """Add a grade to the record.""" if 0 <= grade <= self.MAX_GRADE: self._grades.append(grade) def get_average(self): """Return average grade or 0 if no grades.""" if not self._grades: return 0 return sum(self._grades) / len(self._grades)

Common Mistakes

✕ Mixed Naming
Using camelCase for some functions and snake_case for others in the same file.
✕ Tab/Space Mix
Mixing tabs and spaces causes IndentationError and inconsistent display.
✕ Wildcard Imports
Using "from module import *" pollutes the namespace and hides where names come from.
✕ Over-commenting
Writing comments like "# add 1 to x" for x = x + 1. Only comment why, not what.

PEP 8 Cheat Sheet

Rule Do Don't
Indentation 4 spaces Tabs or 2 spaces
Function names snake_case camelCase
Class names PascalCase snake_case
Line length < 79 characters 200+ character lines
Imports One per line, grouped import os, sys, json
Operators x = y + 1 x=y+1
Blank lines 2 before top-level No blank lines at all

Question 1 of 5

Which naming style does PEP 8 recommend for regular variables and functions?

Question 2 of 5

How many spaces does PEP 8 require per indentation level?

Question 3 of 5

What is the PEP 8 recommended maximum line length for code?

Question 4 of 5

Which import statement follows PEP 8 guidelines?

Question 5 of 5

How many PEP 8 violations can you identify in the code above?