agyanadda@gmail.com

Python Best Practices and Next Steps

Advanced Python 1 min read Updated Dec 4, 2026 Topic 32 of 32

Write Pythonic code

  • Follow PEP 8: 4-space indents, snake_case, clear names
  • Use with for files, f-strings for formatting, enumerate and zip in loops
  • Prefer comprehensions for simple transforms
  • Catch specific exceptions; never use bare except:
  • Small functions that do one thing

Tools

  • Virtual environments for every project
  • Type hints + mypy to catch bugs early
  • Ruff or flake8 (linting) and Black or ruff format (formatting)
  • pytest for tests
  • logging instead of print in real apps

Testing with pytest

pip install pytest, write functions starting with test_ using plain assert, and run pytest.

What to learn next

Path Learn
Web development Django, Flask, FastAPI
Data analysis pandas, NumPy, Matplotlib, Jupyter
AI / ML scikit-learn, PyTorch
Automation Selenium, Playwright, openpyxl

Build projects: a to-do CLI, a weather app with an API, an expense tracker with SQLite, a web scraper, and a Flask or FastAPI REST API.

Example

Example — Typed, logged and tested Python
# calc.py
import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger(__name__)

def emi(principal: float, annual_rate: float, months: int) -> float:
    """Monthly loan EMI."""
    if months <= 0:
        raise ValueError("months must be positive")
    r = annual_rate / 12 / 100
    if r == 0:
        return round(principal / months, 2)
    value = principal * r * (1 + r) ** months / ((1 + r) ** months - 1)
    log.info("EMI for %s at %s%% over %s months = %.2f", principal, annual_rate, months, value)
    return round(value, 2)

# test_calc.py   (run: pytest)
import pytest
from calc import emi

def test_zero_interest():
    assert emi(12000, 0, 12) == 1000

def test_known_value():
    assert emi(100000, 12, 12) == pytest.approx(8884.88, abs=0.01)

def test_invalid_months():
    with pytest.raises(ValueError):
        emi(1000, 10, 0)

pytest runs three tests and reports 3 passed. The function has type hints, a docstring, input checks and logging instead of print.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What is Python's official style guide called?

Exercise 2 True / False

pytest test functions should start with test_.

Exercise 3 Fill in the Blank

Use the ___ module instead of print for messages in real applications.

Frequently Asked Questions

Django if you want a full framework with admin panel, ORM and authentication built in. Flask for small, flexible apps. FastAPI for modern, fast JSON APIs with automatic documentation.