Reference library

Python Code Samples

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

211 matches
Strings & text medium

Convert Natural Language Dates to Datetime in Python

Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.

datetime natural-language regex
Python
from datetime import datetime, timedelta
import re

def parse_natural_date(text: str) -> datetime:
    """Convert common natural language date expressions to datetime objects."""
    now = datetime.now()
    text = text.lower().strip()
    
    # Handle relative dates
    patterns = {
        r"today": now,
        r"…
61 0 Open
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
50 0 Open
Strings & text easy

Repeat a string n times with a separator in Python

Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.

strings repeat join
Python
def repeat_string_with_separator(s, n, sep=''):
    """
    Repeats a string n times, joining with a separator.
    
    Args:
        s (str): The string to repeat.
        n (int): Number of repetitions.
        sep (str): Separator between repetitions (default: '').
    
    Returns:
        str: The repeated strin…
11 0 Open
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
44 0 Open
Lists & loops easy

How to Count Occurrences of a Value in a Python List

Counts how many times a specific value appears in a list using a simple loop and a counter variable.

counting loops lists
Python
def count_occurrences(data, target):
    count = 0
    for item in data:
        if item == target:
            count += 1
    return count


if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    target_value = 5
    result = count_occurrences(numbers, target_value)
    print(f"The value {targ…
13 0 Open
Functions & basics easy

Benchmark list append vs comprehension in Python

This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.

timeit benchmark performance
Python
import timeit

# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
    result = []
    for i in range(n):
        result.append(i)
    return result

# Build the same list using a list comprehension
def comprehension(n=1_000_000):
    return [i for i in range(n)]

if __n…
13 0 Open
Functions & basics easy

Calculate Time Difference Across Time Zones in Python

Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.

datetime timezone timedelta
Python
from datetime import datetime, timezone, timedelta

def time_difference(from_tz_offset, to_tz_offset):
    """
    Calculate time difference in hours between two time zones given their offsets from UTC.
    Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
    """
    tz1 = timezone(timedelta(hours=from_tz_offset…
44 0 Open
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:
                …
11 0 Open
Functions & basics easy

How to Build a Simple Decorator That Logs Function Calls in Python

This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.

decorator logging functools
Python
import functools
import time

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} return…
11 0 Open
Functions & basics easy

How to Compare Two Implementations with timeit in Python

Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.

timeit benchmark performance
Python
import timeit

def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_recursive(n):
    if n == 0:
        return 1
    return n * factorial_recursive(n - 1)

if __name__ == "__main__":
    n = 10
    iterations = 10000

    iterative_time = timeit…
13 0 Open
Functions & basics easy

How to Create a Timing Decorator in Python

A Python decorator that measures and prints the execution time of any function using time.perf_counter.

decorator timing perf_counter
Python
import time
from functools import wraps


def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        elapsed = end - start
        print(f"{func.__name__} took {elapsed:.6f} seconds"…
11 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
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 medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
12 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 easy

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.

retry connection-error error-handling
Python
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…
15 0 Open
Files & data medium

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

work-hours time-tracking csv
Python
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv…
60 0 Open
Files & data medium

Calculate Working Hours Between Two Dates in Python

Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.

datetime working hours business hours
Python
from datetime import datetime, timedelta

def work_hours_between(start: datetime, end: datetime) -> float:
    """Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
    def is_workday(d: datetime) -> bool:
        return d.weekday() < 5
    
    total_hours = 0.0
    current = start
    whi…
48 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:
       …
45 0 Open
Files & data easy

How to Archive Old Files by Age in Python

Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.

file-archiving pathlib shutil
Python
import os
import shutil
import time
from pathlib import Path

def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
    cutoff_time = time.time() - (days_old * 86400)  # 86400 seconds in a day
    archive_path = Path(archive_dir)
    archive_path.mkdir(parents=True, exist_ok=True)

    for i…
46 0 Open
Files & data easy

How to Build a Dated Backup Filename with Timestamp in Python

Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.

datetime backup filenames
Python
from datetime import datetime

def build_backup_filename(base_name: str, extension: str = "bak") -> str:
    """Generate a dated backup filename with timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"

if __name__ == "__main__":
    backup_file = bu…
12 0 Open
Files & data easy

How to Copy a File with shutil.copy2 in Python

Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.

shutil file-copy pathlib
Python
import shutil
from pathlib import Path

source = Path("sample.txt")
destination = Path("sample_copy.txt")

source.write_text("Hello, PythonSkillset!")

if __name__ == "__main__":
    shutil.copy2(source, destination)
    copied = destination.read_text()
    print(f"Copied content: {copied}")
    print(f"Source exists:…
11 0 Open
Files & data easy

How to List File Metadata in Python

This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.

pathlib file-metadata filesystem
Python
from pathlib import Path
import json

def format_files_data(directory_path):
    """Return a list of JSON-serializable dicts with file metadata."""
    base = Path(directory_path)
    if not base.is_dir():
        raise ValueError(f"Not a directory: {directory_path}")

    files_data = []
    for file_path in base.ite…
12 0 Open
Dictionaries & sets medium

How to Build a TTL Cache Dict in Python

Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.

dictionary cache ttl
Python
import time

class TTLDict(dict):
    def __init__(self, ttl, *args, **kwargs):
        self.ttl = ttl
        self._expires = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._expires[key] = time.time() + self.ttl

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