Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

22 matches
Lists & loops easy

How to Safely Convert a List of Strings to Integers in Python

Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.

list conversion int conversion error handling
Python
def safe_to_int(values):
    """Safely convert a list of strings to integers, skipping invalid entries."""
    result = []
    errors = []
    for value in values:
        try:
            result.append(int(value))
        except (ValueError, TypeError):
            errors.append(value)
    return result, errors


if …
13 0 Open
Functions & basics easy

How to Use a Dispatch Table in Python (Map Strings to Functions)

Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.

dispatch-table dictionary functions
Python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b


dispatch = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


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

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

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.

exceptions http-status error-handling
Python
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…
13 0 Open
Files & data easy

How to Convert Images Between Formats in Python

Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.

pillow image conversion file i/o
Python
from PIL import Image
import sys

def convert_image_format(input_path, output_path):
    try:
        img = Image.open(input_path)
        img.save(output_path)
        print(f"Converted {input_path} to {output_path}")
    except FileNotFoundError:
        print(f"Error: File {input_path} not found")
        sys.exit(…
41 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
OOP & classes easy

Python Factory Method: Create Shapes by Type String

A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.

factory-pattern oop polymorphism
Python
class Shape:
    def draw(self):
        raise NotImplementedError


class Circle(Shape):
    def draw(self):
        return "Drawing a circle"


class Square(Shape):
    def draw(self):
        return "Drawing a square"


class Triangle(Shape):
    def draw(self):
        return "Drawing a triangle"


class ShapeFact…
12 0 Open
Automation & scripting easy

How to Clean Old Temp Files in Python

A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.

file-system cleanup pathlib
Python
import os
import time
from pathlib import Path

def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
    """
    Remove files in directory older than the specified age.
    
    Args:
        directory: Path to directory to clean
        max_age_seconds: Maximum age in seconds (default: 1 week)
 …
12 0 Open
Git + Python easy

How to Create a Git Branch if it Doesn't Exist in Python

Utility script that checks if a Git branch exists locally and either creates it or checks it out, with error handling.

git subprocess branch
Python
import subprocess
import sys

def ensure_branch(branch_name):
    """Create a Git branch if it doesn't exist, otherwise checkout it."""
    try:
        # Check if the branch exists locally
        result = subprocess.run(
            ["git", "branch", "--list", branch_name],
            capture_output=True,
         …
10 0 Open
Git + Python easy

How to Mirror a Bare Git Repository Backup in Python

Run a git clone --bare subprocess to create a timestamped bare-repo backup folder with error handling.

git backup subprocess
Python
import subprocess
import shlex
from pathlib import Path
from datetime import datetime


def mirror_bare_repo(source_url: str, backup_dir: str) -> str:
    """Mirror a bare git repository to a timestamped backup folder."""
    backup_path = Path(backup_dir)
    backup_path.mkdir(parents=True, exist_ok=True)

    timest…
12 0 Open
Git + Python easy

How to Push Git Tags to a Remote with Python

Push specified git tags (or all tags) to a remote repository using Python's subprocess module with error handling.

git subprocess automation
Python
import subprocess
import sys


def push_tags_to_remote(remote: str = "origin", tags: list[str] | None = None) -> None:
    """
    Push git tags to a remote repository.
    If no tags are given, push all local tags.
    """
    if tags:
        subprocess.run(["git", "push", remote, *tags], check=True)
    else:
     …
11 0 Open
Git + Python easy

How to Run Git Commands from Python with subprocess

This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.

git subprocess automation
Python
import subprocess


def git_status():
    """Return a short, human-readable git status."""
    try:
        output = subprocess.run(
            ["git", "status", "--short"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        return output if output else "W…
13 0 Open
Cloud + Python easy

How to Parse Cloud JSON Data in Python

A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.

json cloud parsing
Python
import json
from typing import Dict, Any

def parse_cloud_data(payload: str) -> Dict[str, Any]:
    """Parse a JSON payload from a cloud service into a clean dict."""
    try:
        data = json.loads(payload)
        return {
            "status": data.get("status", "unknown"),
            "region": data.get("region…
15 0 Open
Modern tooling easy

How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

mocking bugsnag testing
Python
import mock

bugsnag = mock.MagicMock()

def notify_error(message, severity="error"):
    bugsnag.notify(message, severity=severity)

if __name__ == "__main__":
    notify_error("Test error", severity="warning")
    bugsnag.notify.assert_called_once_with("Test error", severity="warning")
    print("Mocked BugSnag noti…
16 0 Open
Reliability & rate limiting easy

Chaos Inject Random Failures in Python

Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.

chaos-engineering random resilience
Python
import random


def unreliable_function(success_rate: float = 0.7) -> str:
    """Simulate a function that sometimes fails."""
    if random.random() > success_rate:
        raise ConnectionError("Simulated network failure")
    return "Operation completed successfully"


if __name__ == "__main__":
    random.seed(42)…
15 0 Open
Reliability & rate limiting easy

How to Mock Fault Injection Percentage in Python

Simulate a service with a 30% failure rate using random.random to test error handling and retries.

fault-injection random testing
Python
import random

class Service:
    def call(self):
        if random.random() < 0.3:  # 30% failure rate
            raise ConnectionError("Simulated network fault")
        return "ok"

def main():
    svc = Service()
    random.seed(42)  # deterministic for demonstration
    results = []
    for _ in range(10):
     …
14 0 Open
Reliability & rate limiting easy

How to Mock a Try Confirm Cancel Pattern in Python

Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.

try-except mock class
Python
class TCC:
    def __init__(self):
        self.confirmed = False
        self.cancelled = False

    def confirm(self):
        self.confirmed = True
        return "confirmed"

    def cancel(self):
        self.cancelled = True
        return "cancelled"

    def try_confirm(self):
        try:
            result =…
12 0 Open
Observability & SRE easy

How to Ship Logs to an Aggregator Endpoint in Python

Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.

logging requests json
Python
import json
import requests
from datetime import datetime, timezone

LOG_ENTRIES = [
    {"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
    {"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
    {"timestamp": "2024-01-15T10:00:10Z", "level": "E…
13 0 Open
Big data & Spark easy

How to Create a Mock Kafka Producer in Python

Build a Kafka producer that generates mock streaming records with JSON serialization and error handling for local testing.

kafka streaming producer
Python
import json
import time
from kafka import KafkaProducer
from kafka.errors import KafkaError

def create_mock_producer(bootstrap_servers="localhost:9092", topic="input-topic"):
    """Create a Kafka producer that generates mock streaming data."""
    producer = KafkaProducer(
        bootstrap_servers=bootstrap_servers…
16 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.