Reference library

Python Code Samples

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

10 matches
Files & data easy

How to Convert Images Between Formats in Python

Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.

pillow image conversion file i/o
Python
from PIL import Image
import sys

def convert_image_format(input_path, output_path):
    try:
        img = Image.open(input_path)
        img.save(output_path)
        print(f"Converted {input_path} to {output_path}")
    except FileNotFoundError:
        print(f"Error: File {input_path} not found")
        sys.exit(…
39 0 Open
AI & LLM integration patterns easy

How to Parse an LLM Response in Python

This code parses a JSON string from an LLM response, stripping code fences and handling common issues like whitespace, returning a Python dictionary.

llm json parsing
Python
import json
from typing import Any, Dict, List


def parse_llm_response(response: str) -> Dict[str, Any]:
    """Parse a JSON string from an LLM response, handling common edge cases."""
    # Remove code fences if present
    cleaned = response.strip()
    if cleaned.startswith("
13 0 Open
Automation & scripting medium

Build a Website Accessibility Scanner Using Python

Scans a webpage for common accessibility issues like missing alt text, headings, labels, and landmarks using only Python.

accessibility a11y html
Python
import requests
from urllib.parse import urljoin
from html.parser import HTMLParser
import re

class AccessibilityParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.images_without_alt = []
        self.missing_headings = True
        self.has_main_tag = False
        self.label_for_inp…
38 0 Open
Automation & scripting medium

How to Create a Mock Docker Registry Auth Token Server in Python

Build a mock Docker Registry token authentication server that issues signed JWT-like tokens for push and pull access using Python's standard library.

docker registry jwt
Python
import base64
import hashlib
import hmac
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer


class TokenAuthHandler(BaseHTTPRequestHandler):
    """Mock Docker Registry token authentication server."""

    SECRET_KEY = b"mock-secret-key"

    def generate_token(self, username: str, pas…
15 0 Open
Automation & scripting easy

How to Find Stale GitHub Issues in Python

Filter a list of GitHub issues to find those not updated within a configurable number of days using Python datetime arithmetic.

github issues automation
Python
import os
from datetime import datetime, timezone, timedelta
import re

# Simulated GitHub issue data structure
SAMPLE_ISSUES = [
    {"number": 101, "title": "Login button not working", "updated_at": "2025-06-01T12:00:00Z", "assignee": "alice"},
    {"number": 102, "title": "Fix database migration error", "updated_at…
35 0 Open
Automation & scripting medium

How to Scan Configuration Files for Security Issues in Python

Automatically scan configuration files for common security mistakes using regex rules in Python.

security config regex
Python
import re
import os
from pathlib import Path

SECURITY_RULES = [
    (r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
    (r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
    (r'debug\s*=\s*True', 'Debug mode enabled'),
    (r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
48 0 Open
Testing & modern typing easy

How to Compare Floats in pytest with approx

Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.

pytest floating-point testing
Python
import pytest

def test_float_addition():
    result = 0.1 + 0.2
    expected = 0.3
    assert result == pytest.approx(expected)
13 0 Open
Auth & security at scale medium

How to Implement Refresh Token Rotation in Python

A mock auth service that issues, rotates, and validates refresh tokens, revoking old tokens on reuse to prevent replay attacks.

auth oauth refresh-token
Python
import time
import hashlib
import secrets
from typing import Dict, Optional, Tuple


class MockTokenService:
    """Simulates refresh token rotation for a simple auth system."""

    def __init__(self):
        # Token hash -> (user_id, rotation_count, expires_at)
        self._active_tokens: Dict[str, Tuple[str, int,…
11 0 Open
Auth & security at scale medium

How to Implement a Vault Dynamic Database Credentials Mock in Python

A Python dataclass-based mock of HashiCorp Vault that issues short-lived database credentials, tracks leases, and revokes them, demonstrating dynamic secrets rotation.

vault secrets database
Python
import time
import json
from dataclasses import dataclass, field
from typing import Dict


@dataclass
class DynamicCredential:
    username: str
    password: str
    lease_duration: int
    created_at: float = field(default_factory=time.time)

    def is_valid(self) -> bool:
        return time.time() - self.created_…
16 0 Open
Production deployment patterns easy

How to Mock an Ingress TLS Certificate Manager in Python

Build a mock TLS certificate manager for ingress that issues, checks, and renews certificates with expiry tracking — useful for testing deployment workflows before touching real infrastructure.

tls certificates ingress
Python
import ssl
import socket
from datetime import datetime, timedelta


class TLSCertManager:
    def __init__(self, hostname):
        self.hostname = hostname
        self.certificates = {}

    def request_certificate(self, domain, days_valid=90):
        """Mock a certificate issuance request that stores a cert with e…
15 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.