Python Mastery – From Basics to Brilliance / Type Hints and Code Quality

Code Formatting

🧹 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():
    pass

Use PascalCase for classes:

class StudentDetails:
    pass

Use UPPER_CASE for constants:

MAX_SIZE = 100

3️⃣ Spaces

Use spaces around operators:

x = 10 + 5

Not:

x=10+5

4️⃣ Blank Lines

Use blank lines to separate different sections of code.

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b

5️⃣ 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 black

Run it:

black my_file.py

Other popular tools include Ruff and autopep8.