PEP 8
Style Conventions
Master the official Python style guide that makes your code readable, consistent, and professional.
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
The Big Picture of PEP 8
Indentation: 4 Spaces
PEP 8 requires 4 spaces per indentation level. Never mix tabs and spaces. Most editors can convert tabs to spaces automatically.
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
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.
Whitespace Rules
Blank Lines and Spacing
Organizing Imports
PEP 8 requires imports at the top of the file, grouped in a specific order with a blank line between each group:
Comments and Docstrings
How to Apply PEP 8
Example: Fixing Bad Style
Example: Class Formatting
Common Mistakes
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
Code snippet:
class student_record:
MAX_SCORE=100
def GetName(self):
return self.name
How many PEP 8 violations can you identify in the code above?