Python PEP 8 Style Guide
In this page:
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?
# 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
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
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
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
import math # standard library
# import requests # third-party would go next
print(math.pi)
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects