This guide is based on the Python Enhancement Proposal 8 (PEP 8), which provides a coding style guide for Python code. Following these conventions is recommended for all Python projects.
1. Indentation
Use 4 spaces per indentation level.
- Correct Indentation:
if x > 10: print("x is greater than 10")
- Incorrect Indentation:
if x > 10: print("x is greater than 10")
2. Line Length
The maximum line length is 79 characters. If you exceed this length, break the line into logical pieces.
- Correct Line Length:
def function_name(long_name_here, long_argument_name_here, longer_third_argument_name_here): # Function implementation
- Incorrect Line Length:
def function_name(long_name_here, long_argument_name_here, longer_third_argument_name_here, even_longer_fourth_argument_name_here, fifth_argument_name_here): # Function implementation
3. Imports
Imports should be on separate lines and grouped in the following order:
- Standard library imports
- Related third-party imports
- Local application/library specific imports
- Correct Imports:
import os import sys from some import library from .local import library
- Incorrect Imports:
import os, sys, from some import library, from .local import library
4. Strings and Identifiers
Use snake_case for variable and function names. Use uppercase for constants.
- Correct Naming:
my_variable = 10 get_user_info() MAX_VALUE = 100
- Incorrect Naming:
myVariable = 10 get_user_info() MAX_VALUE = 100
5. Comments
Use comments to explain why you're doing something, not what you're doing.
- Correct Comment:
# This is a comment explaining why we're using a while loop here while x < 10: print(x) x += 1
- Incorrect Comment:
# This is a comment explaining how the while loop works while x < 10: print(x) x += 1
For more detailed information, visit the PEP 8 Style Guide on our website.
Python Logo