Reference library

Python Code Samples

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

56 matches
Functions & basics easy

Create a retry decorator with max attempts in Python

A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.

decorator retry error-handling
Python
import functools
import time


def retry(max_attempts, delay=0.1):
    """Retry a function up to max_attempts times on exception."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                …
12 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 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

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
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

Shows how to handle a ValueError with try-except so a bad int() conversion doesn't crash the script.

try-except valueerror error-handling
Python
try:
    number = int("not_a_number")
    print(f"Parsed successfully: {number}")
except ValueError as e:
    print(f"Error: {e}")
    print("Please provide a valid integer.")
print("Program continues running.")
16 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 Exceptions in Python

A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.

exceptions valueerror try-except
Python
def divide_numbers(a, b):
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Please provide numbers, not strings."
    except ValueError:
        return "Error: Invalid value de…
15 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 and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Errors & debugging easy

How to Handle ValueError in Python (try except)

Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.

try-except valueerror error-handling
Python
def divide_numbers(a, b):
    """Divide two numbers and handle ValueError safely."""
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero!"
    except TypeError:
        return "Error: Both inputs must be numbers!"


def parse…
13 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 Handle ValueError with try-except in Python

Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.

error-handling try-except valueerror
Python
def get_number(prompt="Enter a number: "):
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            print("That's not a valid number. Please try again.")


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    ex…
12 0 Open
Errors & debugging easy

How to Inspect Local Variables in an except Block in Python

Capture and print local variables at the moment an exception occurs using locals() inside an except block.

debugging exception-handling locals
Python
def risky_operation(value):
    try:
        result = 10 / value
        return result
    except ZeroDivisionError as e:
        local_vars = dict(locals())
        print(f"Error: {e}")
        print("Local variables at exception:")
        for key, val in local_vars.items():
            print(f"  {key} = {val}")
   …
13 0 Open
Errors & debugging easy

How to Log Exceptions with traceback.format_exc in Python

Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.

traceback logging exception
Python
import traceback
import logging

def risky_operation(value):
    return 10 / value

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def main():
    try:
        result = risky_operation(0)
        print(f"Result: {result}")
    except ZeroDivisionError:
        error_msg =…
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 Raise a Custom Exception with Extra Context in Python

Define a custom exception that carries extra context fields and raise it to provide richer error information.

exceptions custom-exception error-handling
Python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")


def withdraw(balance, amount):
    if amount > balance:
        raise Insuffici…
13 0 Open
Errors & debugging medium

How to Re-raise Exceptions with 'raise from' in Python

Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.

exceptions raise-from error-handling
Python
def divide_with_chain(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError as original_error:
        # Re-raise with explicit chaining context
        raise ValueError("Cannot divide by zero") from original_error

def explain_chain():
    try:
        divide_with_chain(10, 0)
    …
12 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 medium

How to Simulate Timeout with Custom TimeoutError in Python

Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.

timeout threading exceptions
Python
import time
from typing import Callable, TypeVar

T = TypeVar("T")


class TimeoutError(Exception):
    """Raised when an operation exceeds its time limit."""

    def __init__(self, message: str = "Operation timed out"):
        self.message = message
        super().__init__(self.message)


def run_with_timeout(func…
12 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 Use Optional Return in Python Instead of Raising Exceptions

A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.

optional typing dict-get
Python
from typing import Optional


def find_user(users: dict, user_id: int) -> Optional[dict]:
    """
    Look up a user by ID. Returns the user dict if found,
    otherwise returns None instead of raising KeyError.
    """
    return users.get(user_id)


def main() -> None:
    users = {
        1: {"name": "Alice", "ema…
14 0 Open
Errors & debugging easy

How to Use a Fallback Path with FileNotFoundError in Python

Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.

filenotfounderror exceptions fallback
Python
import pathlib

def read_config(path):
    primary = pathlib.Path(path)
    fallback = pathlib.Path("config_backup.json")
    try:
        with primary.open("r") as f:
            return f.read()
    except FileNotFoundError:
        try:
            with fallback.open("r") as f:
                return f.read()
      …
11 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.