Reference library

Python Code Samples

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

98 matches
Lists & loops easy

How to Validate List Data in Python

A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.

validation lists loops
Python
def validate_data(data, expected_types=None, min_length=1):
    """Validate that data is a non-empty list and optionally check item types."""
    if not isinstance(data, list):
        return False, f"Expected a list, got {type(data).__name__}"
    
    if len(data) < min_length:
        return False, f"List must have…
16 0 Open
Functions & basics easy

How to Validate Function Arguments in Python

Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.

validation function arguments type hints
Python
def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle with manual type validation."""
    if not isinstance(length, (int, float)) or isinstance(length, bool):
        raise TypeError(f"length must be a number, got {type(length).__name__}")
    if not isinstance(width, (int,…
13 0 Open
Errors & debugging easy

Catch RecursionError and Fail Gracefully in Python

Wrap a recursive function call in a try-except block to catch RecursionError and print a graceful failure message instead of crashing.

recursion exceptions error-handling
Python
def compute_factorial_recursive(n):
    """Compute factorial recursively, raising RecursionError for deep recursion."""
    if n == 0:
        return 1
    return n * compute_factorial_recursive(n - 1)


if __name__ == "__main__":
    try:
        result = compute_factorial_recursive(10000)
        print(f"Factorial c…
13 0 Open
Errors & debugging easy

Catch ValueError and print friendly message in Python

Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.

error handling try except valueerror
Python
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")
13 0 Open
Errors & debugging easy

How to Assert Preconditions with Descriptive Messages in Python

Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.

assert debugging preconditions
Python
def divide(dividend, divisor):
    assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
    return dividend / divisor


if __name__ == "__main__":
    print(divide(10, 2))
    try:
        divide(10, 0)
    except AssertionError as e:
        print(f"AssertionError: {e}")
15 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 easy

How to Handle ValueError When Converting Strings to Integers in Python

Convert text to an integer with a try-except block that catches ValueError and prints beginner-friendly error messages.

valueerror try-except int
Python
def parse_number(text):
    """Convert text to an integer, showing beginner-friendly error handling."""
    try:
        number = int(text)
        print(f"Successfully parsed: {number}")
        return number
    except ValueError as e:
        print(f"Error: '{text}' is not a valid number.")
        print(f"Debuggin…
11 0 Open
Errors & debugging easy

How to Handle ValueError with try except in Python

Shows a beginner-friendly try/except pattern that catches ValueError when converting text to an integer, prints a helpful message, and returns None instead of crashing.

try-except valueerror error-handling
Python
def parse_number(text):
    try:
        return int(text)
    except ValueError:
        print(f"ValueError: '{text}' is not a valid integer.")
        return None


if __name__ == "__main__":
    user_input = "abc"
    result = parse_number(user_input)
    print(f"Parsing '{user_input}' returned: {result}")

    vali…
14 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)
 …
13 0 Open
Errors & debugging easy

How to Return Success or Error as a Tuple in Python (Result Type Pattern)

Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.

result type error handling tuple unpacking
Python
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
    """Return (True, result) on success, (False, error_message) on failure."""
    if divisor == 0:
        return False, "Error: Division by zero"
    return True, dividend / divisor


if __name__ == "__main__":
    # Success case
    success, r…
10 0 Open
Errors & debugging easy

How to Serialize an Exception to a JSON-Safe Dict in Python

Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.

exceptions json logging
Python
import json
import traceback
from typing import Any


def exception_to_dict(exc: Exception) -> dict[str, Any]:
    """Convert an exception into a JSON-safe dictionary."""
    return {
        "type": type(exc).__name__,
        "message": str(exc),
        "traceback": traceback.format_exc().strip().split("\n")[-3:],
…
15 0 Open
Errors & debugging easy

How to Test Exceptions in Python with pytest.raises

Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.

pytest testing exceptions
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)


def test_divide_by_zero_raises_exact_match():
    with py…
15 0 Open
Errors & debugging easy

How to Validate Input and Raise TypeError in Python

Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.

type checking validation typeerror
Python
def validate_number(value):
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected a number, got {type(value).__name__}")
    return value * 2

if __name__ == "__main__":
    try:
        print(validate_number(5))
        print(validate_number("hello"))
    except TypeError as e:
        print(…
13 0 Open
Errors & debugging easy

How to Validate JSON in Python and Catch JSONDecodeError

A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.

json validation jsondecodeerror
Python
import json

def validate_json(json_string):
    """Try to parse JSON, return (is_valid, data_or_error)."""
    try:
        data = json.loads(json_string)
        return True, data
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

if __name__ == "__main__":
    test_inputs = [
        …
11 0 Open
Errors & debugging medium

How to attach a request ID to exception messages in Python

This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.

contextvars exception-handling logging
Python
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="unknown")

def add_request_id(exc: Exception) -> Exception:
    exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
    return exc

d…
12 0 Open
Errors & debugging easy

How to catch ValueError in Python and print a friendly message

This code defines a function that safely converts text to an integer, catches ValueError, and prints a friendly message instead of crashing.

exception handling valueerror try except
Python
def parse_number(text):
    try:
        return int(text)
    except ValueError:
        print("Oops! That's not a valid number.")
        return None

if __name__ == "__main__":
    result = parse_number("abc")
    if result is None:
        print("Parsing failed.")
    else:
        print(f"Parsed value: {result}")
12 0 Open
Errors & debugging easy

How to handle ZeroDivisionError in Python

Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.

zero-division exception-handling try-except
Python
def safe_divide(a, b):
    """Return a/b if possible, else None when dividing by zero."""
    try:
        return a / b
    except ZeroDivisionError:
        return None


def safe_divide_with_message(a, b):
    """Return a how-to message on divide-by-zero error."""
    try:
        return a / b
    except ZeroDivisio…
13 0 Open
Errors & debugging easy

Log to stderr with Python logging basicConfig

Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.

logging stderr debugging
Python
import logging

def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
        stream=__import__("sys").stderr,
    )
    logger = logging.getLogger("example")
    logger.debug("Debug message")
    logger.info("Info message")
    logger.…
12 0 Open
Errors & debugging medium

Redact secrets from log message formatter in Python

Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.

logging redaction security
Python
import re
import logging

class RedactingFormatter(logging.Formatter):
    """Formatter that masks sensitive data in log messages."""
    
    SENSITIVE_PATTERNS = [
        (re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
        (re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
14 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
OOP & classes medium

Observer Pattern in Python: Notify Listeners

Implement the Observer design pattern in Python with a Subject class that manages listeners and notifies them with messages.

design-pattern observer oop
Python
class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def detach(self, observer):
        self._observers.remove(observer)

    def notify(self, message):
        for observer in self._observers:
            observer.update(me…
12 0 Open
Algorithms & data structures easy

Split a String into Multiple Lines by Width in Python

Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.

strings word-wrap algorithm
Python
def split_message(text, max_width):
    words = text.split()
    rows = []
    current_row = []

    for word in words:
        if len(" ".join(current_row + [word])) > max_width:
            rows.append(" ".join(current_row))
            current_row = [word]
        else:
            current_row.append(word)

    if …
14 0 Open
AI & LLM integration patterns easy

How to Build a System-User-Assistant Message List in Python

Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.

llm dataclass openai
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class Message:
    role: str
    content: str


@dataclass
class Conversation:
    messages: List[Message] = field(default_factory=list)

    def add_system(self, content: str) -> None:
        self.messages.append(Message(role="system", con…
12 0 Open
AI & LLM integration patterns easy

How to Mock OpenAI Tool Call Messages in Python

Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.

openai tool-calls mock
Python
from openai import OpenAI


def mock_tool_call(tool_name: str, arguments: dict) -> dict:
    """Simulate a tool call message in OpenAI style."""
    return {
        "role": "assistant",
        "content": None,
        "tool_calls": [
            {
                "id": "call_" + "a1b2c3d4e5f6",
                "type…
14 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.