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.
