← Back to Tutorials Chapter 16

Miscellaneous Topics

Python miscellaneous utilities

datetime Module

from datetime import datetime, date, time, timedelta

now = datetime.now()
today = date.today()
current_time = time(14, 30, 0)

delta = timedelta(days=7)
next_week = now + delta

formatted = now.strftime("%Y-%m-%d %H:%M:%S")
parsed = datetime.strptime("2025-01-15", "%Y-%m-%d")

math Module

import math

print(math.pi, math.e)
print(math.sqrt(16))     # 4.0
print(math.factorial(5)) # 120
print(math.gcd(12, 18))  # 6
print(math.ceil(4.2))    # 5
print(math.floor(4.8))   # 4

Iterators and Generators

An iterator implements __iter__ and __next__. A generator uses yield to produce a sequence lazily.

class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.limit:
            raise StopIteration
        self.count += 1
        return self.count

# Generator
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Generator expression
squares = (x**2 for x in range(10))

Closures and Decorators

# Closure
def make_multiplier(n):
    def multiplier(x):
        return x * n
    return multiplier

double = make_multiplier(2)
print(double(5))  # 10

# Decorator
from functools import wraps

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "Done"

Recursion

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

def binary_search(arr, target, low, high):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binary_search(arr, target, mid + 1, high)
    else:
        return binary_search(arr, target, low, mid - 1)

Regular Expressions (re)

import re

text = "Contact us at support@example.com or sales@test.org"

emails = re.findall(r"\b[\w.]+@[\w.]+\.\w+\b", text)
print(emails)

if re.search(r"\d{3}-\d{4}", "Call 555-1234"):
    print("Phone number found")

cleaned = re.sub(r"[^a-zA-Z0-9]", "-", "Hello World! 2025")
print(cleaned)

pip and requirements.txt

pip install requests numpy pandas
pip freeze > requirements.txt
pip install -r requirements.txt
pip list --outdated

SQLite

import sqlite3

conn = sqlite3.connect("database.db")
cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
conn.commit()

cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

conn.close()

JSON

import json

data = {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}

json_str = json.dumps(data, indent=2)
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)

Tkinter Basics

import tkinter as tk

root = tk.Tk()
root.title("My App")
root.geometry("300x200")

label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

button = tk.Button(root, text="Click Me", command=root.quit)
button.pack()

root.mainloop()

argparse

import argparse

parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("--input", required=True, help="Input file path")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
parser.add_argument("--count", type=int, default=10, help="Number of items")

args = parser.parse_args()
print(f"Processing {args.input} with count={args.count}")
Exercise: Build a CLI todo-list application using argparse, SQLite for persistence, and datetime for due dates. Implement add, list, complete, and delete commands. Use JSON for export/import functionality.