🧹 Code Formatting & PEP 8
PEP 8 is Python's official style guide. It provides recommendations for writing clean, readable, and consistent Python code.
📏 Common PEP 8 Rules
1️⃣ Indentation
Use 4 spaces for indentation.
if age >= 18:
print("Adult")2️⃣ Naming Conventions
Use snake_case for variables and functions:
student_name = "Tisha"
def calculate_total():
passUse PascalCase for classes:
class StudentDetails:
passUse UPPER_CASE for constants:
MAX_SIZE = 1003️⃣ Spaces
Use spaces around operators:
x = 10 + 5Not:
x=10+54️⃣ Blank Lines
Use blank lines to separate different sections of code.
def add(a, b):
return a + b
def subtract(a, b):
return a - b5️⃣ Line Length
Traditionally, PEP 8 recommends keeping lines to 79 characters or fewer.
For example, break long expressions into multiple lines:
result = calculate_total(
price,
quantity,
discount
)🎨 Code Formatting Tools
You can use tools to automatically format Python code.
Black
pip install blackRun it:
black my_file.pyOther popular tools include Ruff and autopep8.