Reference library

Python Code Samples

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

25 matches
Errors & debugging medium

Collect Multiple Validation Errors in Python Before Raising

A chainable Validator class that accumulates all validation errors and raises them together in a single exception.

validation exceptions errors
Python
class ValidationError(Exception):
    pass

class Validator:
    def __init__(self):
        self.errors = []
    
    def validate_required(self, value, field_name):
        if not value:
            self.errors.append(f"{field_name} is required")
        return self
    
    def validate_email(self, email):
        …
13 0 Open
Errors & debugging easy

How to Catch ValueError in Python (try except)

Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.

errors exception handling valueerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed number: {number}"
    except ValueError as error:
        return f"Error: '{text}' is not a valid number ({error})"


if __name__ == "__main__":
    examples = ["42", "hello", "3.14", "100"]
    for item in examples:
        print(pars…
11 0 Open
Errors & debugging medium

How to Log Errors with Structured Fields in Python

Logs error details as structured dictionary fields using Python's logging module with extra parameters.

logging errors structured
Python
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 …
14 0 Open
Errors & debugging medium

How to Print an Exception Chain in Python for Debugging

A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.

exception-chain debugging traceback
Python
import sys
import traceback

def pretty_exception_chain(exc):
    """Print the full exception chain with cause/context details."""
    chain = []
    current = exc
    seen = set()
    
    while current is not None and id(current) not in seen:
        seen.add(id(current))
        chain.append(current)
        curren…
11 0 Open
Errors & debugging easy

How to Record Last N Errors with a Ring Buffer in Python

Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.

ring-buffer deque error-handling
Python
import collections

class ErrorRecorder:
    def __init__(self, size):
        self.buffer = collections.deque(maxlen=size)

    def record_error(self, message):
        self.buffer.append(message)

    def get_errors(self):
        return list(self.buffer)

if __name__ == "__main__":
    recorder = ErrorRecorder(3)
 …
12 0 Open
Errors & debugging easy

How to Validate an Email Address and Raise ValueError in Python

This code defines a validate_email function that checks an email address against a regex pattern and several rules, raising ValueError with a specific reason when invalid.

validation regex errors
Python
import re

def validate_email(email: str) -> str:
    """Validate an email address and return it if valid, otherwise raise ValueError."""
    if not isinstance(email, str):
        raise ValueError("Email must be a string")
    if len(email) > 254:
        raise ValueError("Email length exceeds 254 characters")

    #…
13 0 Open
Errors & debugging easy

How to check for None and raise helpful errors in Python

A defensive function that explicitly validates data, keys, and values — raising descriptive ValueError and KeyError exceptions before returning a result.

none error-handling validation
Python
def get_value(data, key):
    if data is None:
        raise ValueError("data cannot be None")
    if key not in data:
        raise KeyError(f"key '{key}' not found in data")
    result = data[key]
    if result is None:
        raise ValueError(f"value for key '{key}' is None")
    return result


if __name__ == "__…
14 0 Open
Errors & debugging easy

How to define an exception hierarchy for domain errors in Python

Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.

exceptions domain-errors error-handling
Python
class DomainError(Exception):
    """Base class for all domain errors."""
    pass

class ValidationError(DomainError):
    """Raised when input data fails validation rules."""
    pass

class NotFoundError(DomainError):
    """Raised when a requested entity does not exist."""
    pass

class PermissionDeniedError(Dom…
13 0 Open
Errors & debugging easy

Try Except ValueError in Python: Handle Conversion Errors

Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.

try-except valueerror exception
Python
def convert_to_int(value):
    try:
        return int(value)
    except ValueError as error:
        print(f"Conversion failed: {error}")
        print(f"Problem value was: {repr(value)}")
        return None


def divide_numbers(numerator, denominator):
    try:
        result = numerator / denominator
        retur…
13 0 Open
Errors & debugging easy

Validate try except ValueError handler for beginners — errors debugging

Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.

try except valueerror
Python
def divide_numbers(a, b):
    """Divide two numbers, catching division by zero and value errors."""
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        return None
    except TypeError:
        print("Error: Both arguments must be numbers!")
        retu…
13 0 Open
Files & data easy

Automatically Highlight Data Validation Errors Inside Excel Files in Python

Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.

excel validation openpyxl
Python
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path

def highlight_validation_errors(filepath: str, output_path: str = None):
    wb = openpyxl.load_workbook(filepath)
    red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
    
    for sheet in wb.worksheet…
60 0 Open
Files & data easy

How to Create Nested Directories with pathlib mkdir parents in Python

Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.

pathlib mkdir directories
Python
from pathlib import Path

def create_nested_directories(base_path: str, dirs: list[str]) -> None:
    for directory in dirs:
        path = Path(base_path) / directory
        path.mkdir(parents=True, exist_ok=True)
        print(f"Created: {path}")

if __name__ == "__main__":
    root = "output"
    nested_dirs = ["2…
12 0 Open
Files & data easy

How to Delete a File if it Exists in Python

Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.

pathlib file-deletion file-management
Python
from pathlib import Path

def delete_file_if_exists(file_path: str) -> bool:
    """Delete a file if it exists. Returns True if deleted, False if not found."""
    path = Path(file_path)
    if path.exists():
        path.unlink()
        print(f"Deleted: {path}")
        return True
    else:
        print(f"File not…
13 0 Open
Files & data easy

How to Validate a JSON File in Python

A beginner-friendly Python helper that reads a JSON file, catches common errors, and returns a status dictionary.

json validation file-handling
Python
import json
from pathlib import Path

def get_valid_json_data(file_path: str) -> dict:
    file = Path(file_path)
    if not file.exists():
        return {"status": "error", "message": f"File not found: {file_path}"}
    
    try:
        data = json.loads(file.read_text())
    except json.JSONDecodeError as e:
     …
12 0 Open
Dictionaries & sets easy

Validate dictionary data with sets in Python

Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.

dictionaries sets validation
Python
def validate_data(data, required_keys, allowed_values=None):
    """
    Validate a dictionary against required keys and optional allowed value sets.
    Returns a list of validation errors (empty list if valid).
    """
    errors = []
    
    # Check for missing required keys
    missing = set(required_keys) - set(…
14 0 Open
AI & LLM integration patterns medium

How to Retry LLM Calls on Rate Limit Errors in Python

Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.

llm retry rate-limit
Python
import time
import random


def mock_llm_call():
    """Simulates an LLM API call that may raise a rate limit error."""
    if random.random() < 0.4:  # 40% chance of rate limit
        raise RateLimitError("Rate limit exceeded. Try again later.")
    return {"response": "Hello world from mock LLM"}


class RateLimitE…
14 0 Open
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
20 0 Open
Automation & scripting medium

Find Broken Image References Across a Website in Python

Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.

web scraping crawling broken links
Python
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed

def find_all_links(base_url, max_pages=50):
    visited, to_visit = set(), {base_url}
    while to_visit and len(visited) < max_pages:
        url = to_visit.pop()
 …
36 0 Open
Automation & scripting easy

How to Mock subprocess Calls in Python with unittest.mock

A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.

subprocess unittest.mock vagrant
Python
import subprocess
from unittest.mock import patch, Mock


def run_vagrant(action: str) -> str:
    result = subprocess.run(
        ["vagrant", action],
        capture_output=True,
        text=True,
        check=False,
    )
    return result.stdout.strip()


def vagrant_wrapper(action: str) -> str:
    if action n…
14 0 Open
Cloud + Python easy

How to Implement Retry with Exponential Backoff for Cloud API 429 Errors in Python

Implement a retry-with-backoff loop in Python to handle 429 throttling errors from cloud APIs, using exponential delay between attempts.

retry backoff 429
Python
import time
import random
import requests


def api_call(attempt):
    """Mock cloud API that returns 429 for the first two attempts."""
    if attempt < 2:
        return 429, "Too Many Requests"
    return 200, {"data": "success"}


def retry_with_backoff(api_func, max_retries=3, base_delay=0.1):
    for attempt in …
12 0 Open
Cloud + Python easy

How to Validate AWS Security Group Ingress Rules in Python

Validates AWS security group ingress rules (protocol, port ranges, CIDR, description) and returns a list of errors or OK.

aws security-groups validation
Python
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class SecurityGroupRule:
    protocol: str
    port_range: tuple
    cidr: str
    description: str = ""

def validate_ingress_rule(rule: SecurityGroupRule) -> List[str]:
    """Validate a security group ingress rule against common AWS pat…
10 0 Open
Testing & modern typing easy

How to Write a Fast Smoke Test for a Critical Path in Python

A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.

smoke-test performance health-check
Python
import time

def smoke_test(path):
    if path != "/health":
        raise ValueError("Critical path expected /health")
    start = time.perf_counter()
    # Simulate the critical health check work
    time.sleep(0.01)
    elapsed = time.perf_counter() - start
    if elapsed > 0.05:
        raise RuntimeError("Health …
11 0 Open
Reliability & rate limiting medium

How to Implement a Circuit Breaker in Python

A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.

circuit-breaker resilience fault-tolerance
Python
from dataclasses import dataclass
from datetime import datetime, timedelta
import time


@dataclass
class CircuitBreaker:
    failure_threshold: int = 3
    timeout_seconds: float = 5.0
    failures: int = 0
    state: str = "closed"
    last_failure: datetime = None

    def call(self, func):
        if self.state ==…
14 0 Open
Observability & SRE easy

Calculate Error Rate from Log Stream in Python

Parses a mock log stream to count errors and compute the error percentage using a rolling window of recent entries.

logging regex error-rate
Python
import re
from collections import deque

def error_rate_from_log_stream(message):
    log_pattern = r'^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (ERROR|INFO|DEBUG): (.*)$'
    recent_entries = deque(maxlen=100)
    error_count = 0
    total_count = 0

    for line in message.strip().split('\n'):
        match = re.mat…
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.