
PEP 8 (Python Enhancement Proposal 8) is the official style guide for writing Python code.
It defines coding conventions that improve consistency, readability, and maintainability of Python projects.
πΉ Why is PEP 8 Important?
- Ensures readable and clean code.
- Makes collaboration easier in large teams and open-source projects.
- Prevents confusion by following consistent formatting rules.
- Helps beginners adopt good coding practices.
πΉ Key PEP 8 Recommendations
- Indentation β Use 4 spaces per indentation level (avoid tabs).
- Line Length β Limit code lines to 79 characters (docstrings/comments: 72).
- Naming Conventions:
- Variables & functions β
lowercase_with_underscores
- Classes β
CamelCase
- Constants β
ALL_CAPS
- Variables & functions β
- Blank Lines β Use blank lines to separate functions, classes, and code blocks.
- Imports β One import per line, placed at the top of the file.
- Spaces Around Operators β Use spaces around operators and after commas.
x = 5 + 3 # Good x=5+3 # Bad
- Comments & Docstrings β Write meaningful comments and use triple quotes (
"""
) for docstrings.
πΉ Example (Following PEP 8)
def greet_user(name):
"""Display a simple greeting."""
print(f"Hello, {name}")
greet_user("Alice")
Output:
Hello, Alice
β
Summary:
PEP 8 is the style guide for Python that promotes readable, consistent, and professional code, making it easier to share and maintain projects.