Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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,
…
How to Inspect String Statistics in Python
A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.
def inspect_text(text: str) -> dict:
"""Return useful stats about a string for beginners."""
words = text.split()
return {
"length": len(text),
"word_count": len(words),
"uppercase": sum(1 for ch in text if ch.isupper()),
"lowercase": sum(1 for ch in text if ch.islower()),
…
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
How to Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Memory Map Large Files Read-Only in Python
This code demonstrates reading only the tail of a large file using a read-only memory map (mmap) to avoid loading the entire file into memory.
import mmap
import os
def read_tail_with_mmap(filepath, bytes_from_end=64):
"""Read the last bytes of a large file using a read-only mmap."""
file_size = os.path.getsize(filepath)
start = max(0, file_size - bytes_from_end)
with open(filepath, "rb") as f:
with mmap.mmap(f.fileno(), length=0, a…
Tail last N lines of growing log file in Python
Prints the last n lines of a log file and follows new content appended to it, polling for size changes.
import time
from pathlib import Path
def tail_log(file_path, n=10, poll_interval=1.0, timeout=10):
"""
Print the last n lines and follow new lines appended to a growing log file.
"""
path = Path(file_path)
# Read the last n lines from the current file
with path.open("r", encoding="utf-8") as f…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
How to Tail and Colorize Error Lines in Python
Reads the last N lines of a log file and prints error lines in red using ANSI color codes.
import sys
import time
from pathlib import Path
def tail_colorize(filename: str, lines: int = 20) -> None:
"""Read last N lines of a file, printing errors in red."""
path = Path(filename)
if not path.exists():
print(f"File '{filename}' not found.", file=sys.stderr)
return
# Read last …
Monitor Disk Usage and Alert in Python
A Python script that checks disk usage percentage against a threshold and returns an ALERT or OK message with free space details.
import shutil
import os
def check_disk_usage(path="/", threshold=85.0):
usage = shutil.disk_usage(path)
percent_used = (usage.used / usage.total) * 100
if percent_used > threshold:
return (f"ALERT: Disk usage at {percent_used:.1f}% on {path} "
f"(exceeds {threshold}% threshold…
How to List Failed Records in a Dead Letter Queue Mock in Python
A mock Dead Letter Queue stores failed processing records with error details and timestamps, lists them, and exports to JSON.
import json
from datetime import datetime, timedelta
import random
class DeadLetterQueue:
def __init__(self):
self.failed_records = []
def add_failed_record(self, record_id, payload, error_message):
self.failed_records.append({
"record_id": record_id,
"payload": paylo…
How to Calculate VPC Subnet CIDR Details in Python
Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.
import ipaddress
def subnet_details(cidr: str) -> dict:
network = ipaddress.ip_network(cidr, strict=False)
return {
"network_address": str(network.network_address),
"broadcast_address": str(network.broadcast_address),
"num_addresses": network.num_addresses,
"prefix_length": ne…
How to mock boto3 S3 upload in Python
Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.
import boto3
from unittest.mock import Mock, patch
class S3Uploader:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.client("s3", region_name="us-east-1")
def upload_file(self, local_path, s3_key):
self.s3.upload_file(local_path, self.bucket_name, s3_ke…
Mock AWS Spot Instance Interruption Handler in Python
A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.
import time
import random
class SpotInstanceHandler:
def __init__(self, instance_id):
self.instance_id = instance_id
self.interruption_notices = []
def start(self):
print(f"Spot instance {self.instance_id} started")
def check_interruption(self):
# Simulate random interrup…
How to Create an RFC 7807 Error JSON in Python
Construct a structured error response using the RFC 7807 Problem Details format with a reusable function.
import json
from typing import Dict
def create_rfc7807_error(
type_: str,
title: str,
status: int,
detail: str,
instance: str,
extra_fields: Dict[str, object] | None = None,
) -> str:
"""
Build a JSON string following RFC 7807 Problem Details format.
"""
problem = {
"t…
How to Implement Tail Sampling in Python
Sample the slowest subset of calls (tail) for latency analysis using a deque with a random ratio gate.
import random
import time
from collections import deque
class TailSampler:
def __init__(self, tail_ratio=0.1, max_samples=100):
self.tail_ratio = tail_ratio
self.max_samples = max_samples
self.samples = deque(maxlen=max_samples)
self.total_calls = 0
def record(self, latency_ms…
How to Check Negotiated Cipher Suite in Python
Connect to a TLS server with Python's ssl module and print the negotiated protocol version and cipher suite details.
import ssl
import socket
def get_cipher_suites(hostname, port=443):
context = ssl.create_default_context()
context.set_ciphers("DEFAULT:@SECLEVEL=2")
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
…
How to Build a Data Helper for Production Deployment in Python
Build a reusable DataHelper class that loads configs, validates required keys, normalizes string values, and logs schema details — a production-ready data processing pattern.
import json
from pathlib import Path
from typing import Any, Dict
class DataHelper:
"""Common data processing patterns for production deployment."""
def __init__(self, config_path: str | Path):
self.config_path = Path(config_path)
self.config = self._load_config()
def _load_confi…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.