Loading...

Go Back

Next page
Go Back Course Outline

Python Full Course


Project Work and Best Practices in Python

1. Project Development

Applying Learned Concepts to Real-World Projects

To solidify Python skills, work on projects that incorporate:

  • Data processing (Pandas, NumPy)
  • Web development (Flask/Django)
  • Automation (Scripting)
  • Machine Learning (scikit-learn, TensorFlow)

Example Project: Task Manager (CLI)

# task_manager.py
import json
from typing import List, Dict

class TaskManager:
    def __init__(self, filename: str = "tasks.json"):
        self.filename = filename
        self.tasks = self._load_tasks()

    def _load_tasks(self) -> List[Dict]:
        try:
            with open(self.filename, "r") as f:
                return json.load(f)
        except FileNotFoundError:
            return []

    def _save_tasks(self):
        with open(self.filename, "w") as f:
            json.dump(self.tasks, f, indent=4)

    def add_task(self, title: str, priority: int = 1):
        self.tasks.append({"title": title, "priority": priority, "done": False})
        self._save_tasks()

    def list_tasks(self):
        for idx, task in enumerate(self.tasks):
            status = "✓" if task["done"] else " "
            print(f"{idx + 1}. [{status}] {task['title']} (Priority: {task['priority']})")

    def mark_done(self, task_id: int):
        if 0 <= task_id < len(self.tasks):
            self.tasks[task_id]["done"] = True
            self._save_tasks()

if __name__ == "__main__":
    manager = TaskManager()
    manager.add_task("Learn Python", priority=2)
    manager.add_task("Build a project")
    manager.list_tasks()
Key Features:
  • Persistent storage (JSON file)
  • Type hints for better code clarity
  • Modular structure for maintainability


Project Planning & Execution

  1. Define Requirements
    • What problem does it solve?
    • Who is the user?
  2. Break Down Tasks
    • Use GitHub Issues or Trello
  3. Set Milestones
    • Example: "Basic CLI by Week 1"
  4. Iterate & Improve

Version Control with Git

# Initialize repository
git init

# Check status
git status

# Add files
git add .

# Commit changes
git commit -m "Add task manager CLI"

# Push to remote (GitHub/GitLab)
git remote add origin <repo-url>
git push -u origin main
Best Practices:
  • Write clear commit messages ("Fix login bug" ❌ vs. "Fix incorrect password validation in login" ✅)
  • Use branches for features (git checkout -b feature-auth)
  • Pull before push to avoid conflicts

2. Code Style & Best Practices

PEP 8 Style Guide

Python's official style guide enforces consistency.

Key Rules

CategoryGood ✅Bad ❌
Indentation 4 spaces Tabs or 2 spaces
Line Length ≤ 79 chars Long unbroken lines
Imports Group (stdlib, third-party, local) Mixed imports
Naming snake_case for variables camelCase or PascalCase

Example: PEP 8 Compliant Code

# Good PEP 8 compliant code
import os
from typing import List

def calculate_average(numbers: List[float]) -> float:
    """Compute the arithmetic mean of a list."""
    return sum(numbers) / len(numbers)

Check PEP 8 Compliance

pip install pycodestyle
pycodestyle script.py

Code Readability & Maintainability

  1. Modularize Code
    • Split into functions/classes
    • One responsibility per function
  2. Avoid Magic Numbers
    # Bad
    if temperature > 100:
        alert()
    
    # Good
    BOILING_POINT = 100
    if temperature > BOILING_POINT:
        alert()
  3. Use Constants
    MAX_RETRIES = 3
    API_TIMEOUT = 30  # seconds

Docstrings

Describe what functions/classes do (following Google style):

def factorial(n: int) -> int:
    """Calculates the factorial of a non-negative integer.
    
    Args:
        n: Input number (must be ≥ 0).
    
    Returns:
        Factorial of n.
    
    Raises:
        ValueError: If n is negative.
    """
    if n < 0:
        raise ValueError("n must be non-negative")
    return 1 if n == 0 else n * factorial(n - 1)

Generate Documentation

pip install pdoc
pdoc --html my_module.py

Code Reviews

  1. Checklist:
    • Does it work as intended?
    • Is the code readable?
    • Are there edge cases?
  2. Tools:
    • GitHub Pull Requests
    • pylint for static analysis
      pip install pylint
      pylint script.py


3. Deployment Basics

Options for Deploying Python Apps

TypeToolsUse Case
Scripts Cron (Linux), Task Scheduler (Windows) Automate repetitive tasks
Web Apps Flask: Heroku, Gunicorn + Nginx
Django: AWS, DigitalOcean
Full-stack applications
APIs FastAPI + Uvicorn Microservices
Data Pipelines Apache Airflow Scheduled jobs

Example: Deploying a Flask App on Heroku

  1. Project Structure
    myapp/
    ├── app.py
    ├── requirements.txt
    ├── Procfile
    └── runtime.txt
  2. app.py
    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def home():
        return "Hello, World!"
    
    if __name__ == "__main__":
        app.run()
  3. requirements.txt
    flask
    gunicorn
  4. Procfile
    web: gunicorn app:app
  5. Deploy Steps
    heroku login
    heroku create my-flask-app
    git push heroku main

Virtual Environments

Isolate dependencies per project:

python -m venv venv
source venv/bin/activate  # Linux/Mac
venv\Scripts\activate     # Windows
pip install -r requirements.txt

Summary Table

AreaKey Tools/Practices
Project Planning GitHub Issues, Trello
Version Control Git, GitHub/GitLab
Code Style PEP 8, pycodestyle
Documentation Docstrings, pdoc
Deployment Heroku, Docker, AWS

Final Tips

  • ✅ Start small, then scale
  • ✅ Write tests early (TDD)
  • ✅ Automate deployments (CI/CD)
  • ✅ Document everything

This guide equips you to develop, refine, and deploy Python projects professionally! 🚀

Go Back

Next page