Skip to main content Brad's PyNotes

Appetite Tutorial

TL;DR

Python excels at automation and rapid development with its simple syntax, powerful features, and “batteries included” philosophy - perfect for getting things done quickly.

Interesting!

Python is named after “Monty Python’s Flying Circus” - the documentation even encourages making references to Monty Python sketches and quotes!

The Automation Problem

We all face repetitive tasks on computers:

  • File organization and batch processing
  • Data extraction and formatting
  • System administration scripts
  • Custom database queries
  • GUI applications for specific needs

Traditional solutions have drawbacks:

  • Shell scripts: Limited and platform-specific
  • C/C++/Java: Too much boilerplate for simple tasks
  • Existing tools: Rarely fit your exact needs

Python bridges this gap perfectly!

Why Python Wins

python code snippet start

# Compare a simple task: sum numbers in a file

# C code (simplified)
#include <stdio.h>
int main() {
    FILE *file = fopen("numbers.txt", "r");
    int sum = 0, num;
    while(fscanf(file, "%d", &num) == 1) {
        sum += num;
    }
    fclose(file);
    printf("Sum: %d\n", sum);
    return 0;
}

# Python equivalent
with open("numbers.txt") as f:
    total = sum(int(line) for line in f)
    print(f"Sum: {total}")

python code snippet end

Python advantages:

  • 10x shorter code
  • No memory management
  • Built-in file handling
  • Readable and maintainable

Rapid Development Cycle

python code snippet start

# Python encourages experimentation
>>> data = [1, 2, 3, 4, 5]
>>> sum(data)
15
>>> sum(x**2 for x in data)  # Sum of squares
55
>>> max(data)
5

# Try ideas immediately without compilation!

python code snippet end

High-Level Built-ins

python code snippet start

# Rich data types out of the box
users = {
    'alice': {'age': 30, 'projects': ['web', 'mobile']},
    'bob': {'age': 25, 'projects': ['data', 'ml']}
}

# Filter users by age
experienced = {name: info for name, info in users.items() 
               if info['age'] > 28}

# Flatten all projects
all_projects = [proj for user in users.values() 
                for proj in user['projects']]

python code snippet end

Cross-Platform Power

python code snippet start

import os
import shutil
from pathlib import Path

# Works on Windows, macOS, Linux
def organize_downloads():
    downloads = Path.home() / "Downloads"
    
    for file in downloads.iterdir():
        if file.suffix == '.pdf':
            (downloads / 'PDFs').mkdir(exist_ok=True)
            shutil.move(file, downloads / 'PDFs' / file.name)
        elif file.suffix in ['.jpg', '.png']:
            (downloads / 'Images').mkdir(exist_ok=True)
            shutil.move(file, downloads / 'Images' / file.name)

# Single script works everywhere!

python code snippet end

Perfect for Professionals

System Administrators:

python code snippet start

# Check disk usage across servers
import subprocess
import json

def check_disk_usage(servers):
    for server in servers:
        result = subprocess.run(['ssh', server, 'df -h'], 
                              capture_output=True, text=True)
        print(f"{server}: {result.stdout}")

python code snippet end

Data Analysts:

python code snippet start

# Quick data analysis
import csv
from collections import Counter

def analyze_sales(filename):
    with open(filename) as f:
        reader = csv.DictReader(f)
        products = [row['product'] for row in reader]
        return Counter(products).most_common(5)

python code snippet end

Testers:

python code snippet start

# Automated testing
import requests

def test_api_endpoints():
    endpoints = ['/users', '/products', '/orders']
    base_url = 'https://api.example.com'
    
    for endpoint in endpoints:
        response = requests.get(base_url + endpoint)
        assert response.status_code == 200
        print(f"✓ {endpoint} working")

python code snippet end

Extensible When Needed

python code snippet start

# When Python isn't fast enough, extend with C
import numpy as np  # C extensions for numerical computing

# NumPy operations run at C speed
large_array = np.random.random(1000000)
result = np.mean(large_array)  # Blazingly fast

# Best of both worlds: Python simplicity + C performance

python code snippet end

Design Philosophy Highlights

Readability Counts:

python code snippet start

# Python reads like English
if user.is_authenticated() and user.has_permission('read'):
    display_content()
else:
    redirect_to_login()

python code snippet end

Simple Syntax:

python code snippet start

# No semicolons, braces, or declarations needed
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Clean and expressive

python code snippet end

Indentation Matters:

python code snippet start

# Structure is visual
def process_data(items):
    for item in items:
        if item.is_valid():
            result = item.process()
            if result.success:
                save_result(result)
            else:
                log_error(result.error)
        else:
            skip_item(item)

# No ambiguity about code blocks!

python code snippet end

Rich Ecosystem

“Batteries Included” - Extensive standard library:

  • json - JSON handling
  • sqlite3 - Database operations
  • urllib - Web requests
  • csv - Spreadsheet data
  • email - Email processing
  • xml - XML parsing
  • zipfile - Archive handling
  • datetime - Date/time operations

Vast Third-Party Libraries:

  • requests - HTTP for humans
  • pandas - Data analysis
  • flask/django - Web frameworks
  • numpy/scipy - Scientific computing
  • matplotlib - Plotting
  • pygame - Game development

When to Choose Python

Perfect for:

  • Automation scripts
  • Rapid prototyping
  • Data processing
  • Web development
  • Testing and QA
  • System administration
  • Scientific computing
  • Machine learning

Maybe not ideal for:

  • Real-time systems
  • Mobile app development (primary choice)
  • System-level programming
  • Performance-critical applications

Getting Started

python code snippet start

# Your first useful Python script
import os
import datetime

def backup_important_files():
    """Simple backup script"""
    important_dirs = ['Documents', 'Pictures', 'Projects']
    backup_root = f"backup_{datetime.date.today()}"
    
    os.makedirs(backup_root, exist_ok=True)
    
    for directory in important_dirs:
        if os.path.exists(directory):
            shutil.copytree(directory, 
                          os.path.join(backup_root, directory))
            print(f"✓ Backed up {directory}")

# Run it!
if __name__ == "__main__":
    backup_important_files()

python code snippet end

Python transforms complex automation tasks into simple, readable scripts that work everywhere. Whether you’re organizing files, analyzing data, or building applications, Python gets you from idea to solution faster than any other language!

This introduction sets the stage for using the Python interpreter and exploring Python's basic features . The automation capabilities shown here rely heavily on Python's module system and file handling for real-world applications.

Reference: Whetting Your Appetite