Reference library

Python Code Samples

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

87 matches
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 medium

Create a Python Tool That Generates Professional Excel Dashboards

Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.

openpyxl excel dashboard
Python
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

def create_sales_dashboard(workbook_path: str) -> None:
    """Generate a professional sales dashboard in an Excel workbook."""
    wb = op…
49 0 Open
Files & data easy

Generate Timesheet Reports from Daily Logs in Python

Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.

timesheet reporting aggregation
Python
import json
from pathlib import Path
from collections import defaultdict

def generate_timesheet_report(daily_logs: list[dict]) -> str:
    """
    Generate a timesheet report from daily log entries.
    
    Args:
        daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
    
    Returns:
       …
46 0 Open
Files & data medium

How to Automatically Merge Hundreds of Excel Files Without Losing Formatting in Python

Merge all .xlsx files in a folder into a single Excel workbook, preserving individual sheet structures with sheet name prefixes.

excel pandas merge
Python
import pandas as pd
from pathlib import Path

def merge_excel_files(folder_path: str, output_path: str) -> None:
    """
    Merge all .xlsx files in a folder into a single Excel file,
    preserving individual sheet structures.
    """
    folder = Path(folder_path)
    excel_files = list(folder.glob("*.xlsx"))
    
…
46 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
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 0 Open
Files & data easy

How to Load and Save JSON Files in Python

Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.

json files pathlib
Python
import json
from pathlib import Path


def load_json(filepath: str) -> dict:
    """Load JSON data from a file."""
    path = Path(filepath)
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def save_json(filepath: str, data: dict) -> None:
    """Save data to a JSON file with pretty format…
11 0 Open
Files & data medium

How to Parse Apache Log Files in Python

Parse Apache common log format lines into structured dictionaries using Python's standard library.

apache regex log-parsing
Python
import re
from pathlib import Path

def parse_apache_line(line):
    pattern = r'^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d{3}) (\S+)'
    match = re.match(pattern, line)
    if not match:
        return None
    ip, ident, user, timestamp, method, path, protocol, status, size = match.groups()
    return …
15 0 Open
Dictionaries & sets easy

How to Map Dictionary Values with a Transformation Function in Python

Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.

dictionaries mapping comprehension
Python
def transform_dict_values(d, func):
    """Apply a transformation function to every value in a dictionary."""
    return {key: func(value) for key, value in d.items()}


if __name__ == "__main__":
    original = {"a": 1, "b": 2, "c": 3}
    doubled = transform_dict_values(original, lambda x: x * 2)
    print(doubled)
…
14 0 Open
OOP & classes easy

Group Data Helper Class in Python

A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.

class grouping helper
Python
class GroupData:
    """A simple helper class to store and group data for beginners."""

    def __init__(self):
        self.items = []

    def add(self, item, group):
        """Add an item under a given group name."""
        self.items.append({"item": item, "group": group})

    def get_groups(self):
        """R…
14 0 Open
OOP & classes easy

How to Create a Data Formatter Class in Python

A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.

oop class formatting
Python
class DataFormatter:
    """Helper class for beginners to format common data types."""
    
    def __init__(self, name="data"):
        self.name = name
        self.records = []
    
    def add_record(self, key, value):
        """Add a key-value record to the formatter."""
        self.records.append({"key": key, …
12 0 Open
OOP & classes easy

Python Adapter Class: Wrap Legacy Interface

Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.

adapter design-pattern oop
Python
class LegacySystem:
    """Legacy interface - old method names and parameter format."""
    def query_employee_info(self, emp_id, emp_name):
        return f"Legacy: {emp_id} - {emp_name}"

    def update_employee_department(self, emp_id, department_code):
        return f"Legacy: Updated {emp_id} to dept {department_…
13 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators to Format Data in Python

A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.

list comprehension generators formatting
Python
def format_data(items):
    """Format a list of dictionaries into readable strings."""
    formatted = [
        f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
        for item in items
        if item.get('value', 0) > 0
    ]
    return formatted if formatted else ["No positive values found"]


def g…
13 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators to Transform Data in Python

Transform a list of integers by squaring even numbers with a list comprehension and cubing odd numbers with a generator.

comprehensions generators list-comprehension
Python
def transform_data(data):
    """
    Transform a list of integers:
    - squares of even numbers using a list comprehension
    - cubes of odd numbers using a generator
    """
    squares = [num ** 2 for num in data if num % 2 == 0]
    cubes = (num ** 3 for num in data if num % 2 != 0)
    return squares, cubes


i…
15 0 Open
AI & LLM integration patterns easy

How to Append Few-Shot Examples to a Prompt in Python

This code builds a complete LLM prompt by appending few-shot examples in alternating user/assistant format using a simple loop.

prompt-engineering few-shot llm
Python
def append_few_shot_examples(prompt: str, examples: list[tuple[str, str]], separator: str = "\n\n") -> str:
    """Append few-shot examples to a prompt in alternating user/assistant format."""
    full_prompt = prompt
    for user_input, assistant_output in examples:
        full_prompt = f"{full_prompt}{separator}Use…
15 0 Open
AI & LLM integration patterns medium

How to Build a Data Helper for LLM Prompts in Python

A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.

llm prompt-engineering data-prep
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper class for working with data in AI/LLM pipelines."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
        self.data = data or {}
    
    def flatten(self, prefix: str = "") -> Dict[str, Any]…
17 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
AI & LLM integration patterns easy

Serialize and Format Data for LLM Prompts in Python

Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.

dataclasses json llm
Python
import json
from dataclasses import dataclass, asdict


@dataclass
class Recipe:
    """Simple data model to represent a recipe."""
    name: str
    cuisine: str
    prep_minutes: int


def to_json(recipe: Recipe) -> str:
    """Serialize a Recipe to a JSON string."""
    return json.dumps(asdict(recipe), indent=2)

…
14 0 Open
Automation & scripting medium

Convert HTML Tables to Excel Reports in Python

Convert HTML tables into formatted Excel reports using BeautifulSoup and Pandas with auto-adjusted column widths.

html excel beautifulsoup
Python
import pandas as pd
from bs4 import BeautifulSoup
from pathlib import Path

def html_table_to_excel(html_file: str, excel_file: str) -> None:
    """Convert HTML table to formatted Excel report."""
    with open(html_file, 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    soup = BeautifulSoup(html_…
46 0 Open
Automation & scripting easy

Create ICS Calendar Invites in Python

This script generates a batch of calendar invites in the ICS format using the ics library.

ics calendar automation
Python
import ics
from datetime import datetime, timedelta

def create_invites(batch):
    calendar = ics.Calendar()
    for event_data in batch:
        event = ics.Event()
        event.name = event_data["name"]
        event.begin = event_data["start"]
        event.end = event_data["end"]
        event.description = even…
11 0 Open
Automation & scripting medium

Extract Attachments from mbox Mailbox Files in Python

Extract file attachments from an mbox mailbox format using Python's standard library email and mailbox modules.

mbox email attachments
Python
import email
import mailbox
from email.policy import default
from pathlib import Path

def extract_attachments(mbox_path, output_dir):
    output_dir = Path(output_dir)
    output_dir.mkdir(exist_ok=True)
    mbox = mailbox.mbox(mbox_path)
    
    for msg in mbox:
        if msg.is_multipart():
            for part i…
13 0 Open
Automation & scripting easy

Fill PDF Form Fields from a Mock Template in Python

Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.

pdf forms json
Python
import json

template = {
    "first_name": "",
    "last_name": "",
    "email": "",
    "phone": "",
    "date_of_birth": "",
    "address": "",
    "city": "",
    "state": "",
    "zip_code": "",
    "agree_to_terms": False
}


def fill_pdf_form(template: dict, data: dict) -> dict:
    for key, value in data.items…
10 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
37 0 Open
Automation & scripting medium

Find the Largest Files Consuming Disk Space with a Beautiful Terminal Report in Python

Scan a directory recursively and print a formatted terminal report of the largest files, with human-readable sizes.

file-system disk-space pathlib
Python
import os
import sys
from pathlib import Path

def get_largest_files(directory: str, count: int = 10) -> list:
    """
    Scan the given directory and return the largest files.
    
    Args:
        directory: Path to the directory to scan
        count: Number of largest files to return
        
    Returns:
      …
44 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.