Reference library

Python Code Samples

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

17 matches
Strings & text easy

How to Build a Text Processor in Python

This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.

text-processing strings word-count
Python
def count_words(text):
    return len(text.split())


def count_sentences(text):
    sentence_endings = ".!?"
    count = 0
    for char in text:
        if char in sentence_endings:
            count += 1
    return count


def longest_word(text):
    words = text.split()
    if not words:
        return ""
    retur…
14 0 Open
Strings & text easy

How to Compare Two Strings in Python

Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.

string-comparison case-insensitive helper-function
Python
def compare_data(first_value, second_value):
    """Compare two string values and return a report."""
    if first_value == second_value:
        status = "MATCH"
    else:
        status = "DIFFER"
    return {
        "first_value": first_value,
        "second_value": second_value,
        "status": status,
       …
12 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.

lists loops enumerate
Python
# text_processor.py

def process_text(lines):
    """Count words, show uppercase, and count characters per line."""
    total_words = 0
    print("Line-by-line analysis:")
    for i, line in enumerate(lines, start=1):
        words = line.split()
        total_words += len(words)
        print(f"  Line {i}: {len(words…
17 0 Open
Errors & debugging easy

Handle ValueError and ZeroDivisionError in Python with try except

Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.

try-except valueerror zerodivisionerror
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ValueError as e:
        print(f"ValueError caught: {e}")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    return result

# Test cases
print(safe_divide…
12 0 Open
Files & data medium

Create a Local File Versioning System Using Pure Python

Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.

file-versioning files backup
Python
import os
import shutil
import hashlib
import json
import time
from pathlib import Path

class LocalFileVersioning:
    def __init__(self, target_dir="versioned_files", versions_dir="versions"):
        self.target_dir = Path(target_dir)
        self.versions_dir = Path(versions_dir)
        self.metadata_file = self.…
51 0 Open
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
14 0 Open
OOP & classes easy

How to Implement Iterator Protocol on a Custom Class in Python

Create a custom iterable class by defining the __iter__ and __next__ methods, enabling use in for loops and list conversions.

iterator protocol class
Python
class Countdown:
    """Iterator that counts down from start to 0."""

    def __init__(self, start):
        self.start = start
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < 0:
            raise StopIteration
        value = self.current
 …
12 0 Open
Automation & scripting easy

How to Build a Docker Image Tag Script in Python

Generate consistent Docker image tags from service names and versions with automatic normalization.

docker scripting cli
Python
#!/usr/bin/env python3
"""Mock script for building docker image tags."""


def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
    """Construct a docker image tag."""
    safe_name = service_name.lower().replace("_", "-")
    return f"{registry}/{safe_name}:{version}"


if __name__ == "…
12 0 Open
Automation & scripting easy

How to Generate an Inventory CSV of Installed pip Packages in Python

This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.

pip csv subprocess
Python
import subprocess
import csv

def get_installed_packages():
    """Return a list of (name, version) tuples for installed pip packages."""
    result = subprocess.run(
        ["pip", "list", "--format=freeze"],
        capture_output=True,
        text=True,
        check=True
    )
    packages = []
    for line in r…
13 0 Open
Automation & scripting easy

Pin Python package versions in requirements.txt

Pin package versions in requirements.txt-style text by adding ==version when no specifier is present, while preserving existing version constraints and comments.

requirements automation versions
Python
import re
from pathlib import Path


def pin_versions(requirements_text: str) -> str:
    """
    Pin package versions in requirements.txt-style text.
    Adds ==version if no version specifier is present.
    Keeps existing specifiers (>=, <=, ~=, etc.) unchanged.
    """
    lines = requirements_text.strip().splitli…
14 0 Open
Cloud + Python easy

Mock GCP Secret Manager access version in Python

A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.

gcp secret-manager mock
Python
import json
import time
from datetime import datetime, timezone


class MockSecretManager:
    """Minimal mock of GCP Secret Manager access/version behavior."""

    def __init__(self):
        self._secrets = {}
        self._access_log = []

    def create_secret(self, secret_id: str, payload: str) -> dict:
        …
15 0 Open
Modern tooling easy

Mock pip-compile to Resolve Requirements in Python

A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.

pip-tools requirements mock
Python
import subprocess
import tempfile
from pathlib import Path


def compile_requirements_mock(requirements_in: str) -> str:
    """Mock pip-compile: resolve a simple requirements.in into a locked format."""
    lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
  …
12 0 Open
API design & gRPC medium

Version API by Accept Header with Vendor Media Types in Python

Build a mock HTTP server that routes to API versions by parsing vendor-specific Accept headers in Python.

api-versioning accept-header http-server
Python
from http.client import HTTPMessage
from http.server import BaseHTTPRequestHandler, HTTPServer


class VendorVersionHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        accept = self.headers.get("Accept", "")
        version = "v1"
        if "application/vnd.myapi.v2+json" in accept:
            version = "…
13 0 Open
Microservices patterns easy

How to Mock Service Versioning URI in Python

Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.

http-server versioning mock
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json


class VersionedHandler(BaseHTTPRequestHandler):
    def _send_json(self, payload, status=200):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
    …
11 0 Open
ML engineering pipelines easy

How to implement a canary traffic split in Python

Route incoming traffic between stable and canary model or service versions using a weight-based random split with deterministic testing.

canary traffic-split random
Python
import random


def canary_route(service_name: str, canary_weight: float = 0.2) -> str:
    """Route traffic between stable and canary versions based on weight."""
    rng = random.Random(42)  # deterministic for reproducible demo
    if rng.random() < canary_weight:
        return f"{service_name}-canary"
    return …
14 0 Open
ML engineering pipelines easy

Model registry version mock in Python

A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.

ml-engineering model-registry versioning
Python
class ModelRegistry:
    def __init__(self):
        self.models = {}

    def register(self, name, version, model_type, metrics=None):
        if name not in self.models:
            self.models[name] = []
        entry = {
            "version": version,
            "model_type": model_type,
            "metrics": m…
13 0 Open
Production deployment patterns medium

How to Simulate Blue-Green Deployment Switch in Python

A mock Blue-Green deployment class that deploys new versions to an inactive environment, runs a health check, switches traffic, and supports rollback in Python.

deployment blue-green mock
Python
import random
import time

class BlueGreenDeployment:
    def __init__(self, initial_env="blue"):
        self.environments = {"blue": "v1.0", "green": "v1.0"}
        self.active_env = initial_env
        self.running = True

    def deploy_new_version(self, version, target_env):
        if target_env == self.active_…
16 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.