Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

45 matches
Automation & scripting easy

How to Scan Files Against a Malware Hash List in Python

Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.

hashlib file-scanning security
Python
import hashlib
from pathlib import Path

# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"

KNOWN_MALWARE_HASHES = {
    "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}

def sha25…
14 0 Open
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
42 0 Open
Automation & scripting easy

How to generate website performance reports from HTTP requests in Python

Measure and report website load time, status code, and content size using Python's standard library.

http performance urllib
Python
import urllib.request
import time

def measure_website_load_time(url):
    """Measures total loading time of a website."""
    start_time = time.time()
    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            content = response.read()
            status_code = response.status
            …
38 0 Open
Git + Python easy

Detect Merge Conflict Markers in a File with Python

Scan a file line by line to detect Git merge conflict markers (<<<<<<<, =======, >>>>>>>) and report their line numbers with context.

git merge-conflict file-scanning
Python
from pathlib import Path

def detect_merge_conflicts(file_path):
    conflicts = []
    with open(file_path, 'r') as f:
        lines = f.readlines()
    
    for i, line in enumerate(lines, 1):
        if line.startswith('<<<<<<<'):
            conflict_marker = 'conflict start'
            conflicts.append((i, confl…
14 0 Open
Cloud + Python easy

How to Enforce Tag Policies on AWS Resources in Python

Build a reusable Python class that checks AWS resources against a required-tag policy and reports compliance with missing tags.

aws tagging compliance
Python
import json
from dataclasses import dataclass, field
from typing import Dict, List


@dataclass
class Resource:
    arn: str
    tags: Dict[str, str] = field(default_factory=dict)


class TagPolicyEnforcer:
    def __init__(self, required_tags: List[str]):
        self.required_tags = set(required_tags)

    def enfor…
15 0 Open
Modern tooling easy

How to Generate a Mock Rollbar Error Report in Python

Create a realistic fake Rollbar error report with random timestamps, levels, messages, and counts for testing and demos.

rollbar mock-data error-reporting
Python
import json
import random
import time
from datetime import datetime, timedelta


def mock_rollbar_report(n_errors=5):
    messages = [
        "TypeError: unsupported operand type(s) for +: 'int' and 'str'",
        "KeyError: 'user_id'",
        "ValueError: invalid literal for int() with base 10: 'abc'",
        "At…
13 0 Open
Modern tooling easy

How to Run Coverage Report and Generate HTML in Python

Use the coverage module to measure test coverage, save the report, and generate an HTML report in Python.

coverage testing unittest
Python
import coverage
import unittest


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


class TestAdd(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)


if __name__ == "__main__":
    cov = coverage.Coverage(source=["__main__"])
    cov.start()
    suite = unittest.defaultTestLoader.loadTestsFro…
12 0 Open
Concurrency & performance medium

Build a Python Performance Profiler That Generates Readable Reports

Use cProfile and pstats to profile Python functions and print a sorted performance report showing the top time-consuming calls.

profiling cprofile pstats
Python
import cProfile
import pstats
import io
from pathlib import Path

def slow_function():
    total = 0
    for i in range(500_000):
        total += i ** 2
    return total

def fast_function():
    total = sum(i * i for i in range(500_000))
    return total

def profile_functions():
    profiler = cProfile.Profile()
  …
44 0 Open
Concurrency & performance medium

How to Profile CPU Hot Path in Python with cProfile and sort_stats cumtime

Profile a Python function's CPU usage by running cProfile, sorting stats by cumulative time, and printing a readable report to stdout.

cprofile profiling performance
Python
import cProfile
import pstats
import io


def slow_function():
    total = 0
    for i in range(100_000):
        total += i * i
    return total


def fast_function():
    return sum(i for i in range(100))


def main():
    slow_function()
    fast_function()


if __name__ == "__main__":
    profiler = cProfile.Profi…
12 0 Open
Testing & modern typing medium

How to Run Test Coverage with pytest-cov in Python

Run pytest with coverage reporting using pytest-cov on a temporary project and see line-by-line coverage output.

pytest coverage testing
Python
import os
import subprocess
import tempfile
from pathlib import Path


def sample_function(x: int) -> int:
    """A simple function to demonstrate coverage."""
    if x > 0:
        return x * 2
    else:
        return -x


def run_pytest_with_coverage() -> str:
    """Run pytest with coverage on a temp project and r…
14 0 Open
Reliability & rate limiting easy

How to Implement a Temporary Block in Python

Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.

rate-limiting penalty-box lockout
Python
class PenaltyBox:
    def __init__(self, block_seconds: int = 30):
        self.block_seconds = block_seconds
        self._blocked_until = 0.0
        self._attempts = 0

    def try_access(self, current_time: float) -> bool:
        if self._blocked_until and current_time < self._blocked_until:
            return Fa…
14 0 Open
Observability & SRE easy

How to Build a Consumer Lag Gauge in Python

Simulate Kafka consumer lag with a Python class that tracks lag over time and reports health and averages.

consumer-lag kafka monitoring
Python
import time
import random
from collections import deque


class ConsumerLagGauge:
    """Mock consumer lag gauge measuring how far behind a consumer is."""

    def __init__(self, producer_rate=10, consumer_rate=7, initial_lag=0):
        self.producer_rate = producer_rate
        self.consumer_rate = consumer_rate
  …
13 0 Open
Observability & SRE easy

How to Check Service Readiness Dependencies in Python

This code simulates a readiness check for external dependencies (database, cache, queue) with mock availability data and reports readiness status.

readiness dependencies health-check
Python
import sys
from datetime import datetime


def check_dependencies(config):
    results = []
    for dep, required in config.items():
        available = mock_availability(dep)
        status = "READY" if available >= required else "NOT READY"
        results.append((dep, available, required, status))
    return result…
11 0 Open
Observability & SRE easy

How to Create a Deep Health Check Database in Python

Setup a SQLite-backed health check database, insert mock data with response times and statuses, and generate a report ordered by most recent check.

sqlite health-check database
Python
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

DB_PATH = Path("deep_health_check.db")


def setup_database():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS health_checks (
            id INTEGER PRIMARY KEY AU…
14 0 Open
Observability & SRE easy

Mock Health Endpoint Liveness Check in Python

Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.

health check mock observability
Python
import time
import random


def liveness_check(service_name: str, failure_rate: float = 0.1) -> dict:
    """Mock health check that returns liveness status with a configurable failure rate."""
    healthy = random.random() > failure_rate
    response = {
        "service": service_name,
        "status": "alive" if he…
16 0 Open
Observability & SRE easy

Track Success Rates and Latency in Python: SRE Metrics Helper

A beginner-friendly Python class to record request outcomes and latencies, then report success rate, average latency, and p99.

sre metrics latency
Python
import random
import time
from collections import defaultdict


class MetricsTracker:
    """Simple helper to track success rates and latencies for SRE beginners."""

    def __init__(self):
        self.successes = 0
        self.failures = 0
        self.latencies = []

    def record(self, success, latency_ms):
   …
14 0 Open
ML engineering pipelines easy

Compare Model A vs Model B Metrics in Python

A script that simulates and compares metrics between two ML models, showing a formatted diff table for quick insight.

model comparison mock metrics
Python
import random


def compare_a_b(samples=5):
    """Mock comparison of model A vs model B predictions."""
    metrics = ["accuracy", "precision", "recall", "f1"]
    print(f"{'Metric':<12}{'Model A':>10}{'Model B':>10}{'Diff':>10}")
    print("-" * 42)

    random.seed(42)
    for metric in metrics:
        a = round(r…
14 0 Open
A/B testing & experimentation easy

Generate a Mock Multi-Armed Bandit Report in Python

Simulate a multi-armed bandit experiment with random pulls and rewards, then output a JSON report with per-arm statistics.

bandit simulation random
Python
import random
import json

def generate_mock_bandit_report(num_arms=5, num_rounds=100, seed=42):
    random.seed(seed)
    arms = ["A", "B", "C", "D", "E"][:num_arms]
    true_means = {arm: random.uniform(0.3, 0.7) for arm in arms}
    pulls = {arm: 0 for arm in arms}
    rewards = {arm: 0 for arm in arms}

    for _ …
16 0 Open
Database scaling & optimization easy

Monitor Database Index Bloat in Python

Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.

database index monitoring
Python
import random
import time

class IndexBloatMonitor:
    def __init__(self, thresholds=(0.5, 0.8, 0.9)):
        self.thresholds = thresholds
        self.indices = {
            "users_pk": 48.2,
            "orders_created_idx": 124.7,
            "products_name_idx": 15.3,
            "payments_user_idx": 203.9,
   …
15 0 Open
Production deployment patterns easy

How to Build a Synthetic Monitor Mock in Python

Simulates a synthetic monitoring system in Python that collects latency samples, averages them, and reports service status as UP or DEGRADED.

monitoring dataclass simulation
Python
import random
import time
from dataclasses import dataclass, field
from statistics import mean


@dataclass
class SyntheticMonitor:
    service: str
    endpoint: str
    latency_ms: list[float] = field(default_factory=list)

    def check(self) -> float:
        latency = random.uniform(50.0, 250.0)
        self.late…
13 0 Open
Production deployment patterns easy

How to Implement a Data Helper Class in Python for Production Deployments

Build an environment-aware data helper in Python that loads config, extracts, transforms, and reports on JSON data using small, testable functions.

data-helper production json
Python
"""Production-style data helper for beginners.

Demonstrates:
- environment-aware config
- central data extraction
- small, testable functions
"""

import os
import json
from pathlib import Path
from typing import List, Dict, Any


def load_config(env: str = os.getenv("APP_ENV", "development")) -> Dict[str, Any]:
    …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.