Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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…
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.
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):
…
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.
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}")
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:
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.")
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.
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…
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.
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…
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.
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…
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.
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 =…
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.
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…
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.
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…
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.
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)
…
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.
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:],
…
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.
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…
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.
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…
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.
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…
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.
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()
…
How to Use pdb.post_mortem in Python
Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.
import pdb
import sys
def divide(a, b):
return a / b
def main():
try:
result = divide(10, 0)
print(f"Result: {result}")
except Exception:
# Enter post-mortem debugging when an uncaught exception occurs
pdb.post_mortem(sys.exc_info()[2])
if __name__ == "__main__":
main…
How to Wrap a Low Level Error in a Higher Level Exception in Python
Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.
class LowLevelError(Exception):
pass
class HighLevelError(Exception):
pass
def low_level_operation():
raise LowLevelError("storage drive failed to respond")
def high_level_operation():
try:
low_level_operation()
except LowLevelError as e:
raise HighLevelError(f"database operation…
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.
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__ == "__…
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.
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…
How to parse a traceback to get the last frame in Python
Extracts the innermost frame's file, line, and function name from a Python traceback object.
import sys
import traceback
def parse_traceback_last_frame(exc_info):
"""Return the file, line, and function of the last (innermost) frame."""
_, _, tb = exc_info
last_tb = tb
while last_tb.tb_next is not None:
last_tb = last_tb.tb_next
filename = last_tb.tb_frame.f_code.co_filename
l…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
EXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_S…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
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.