Reference library

Python Code Samples

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

121 matches
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…
51 0 Open
Strings & text easy

How to Validate Text Input in Python: A Simple Text Processor

A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.

text-validation strings input-checking
Python
def validate_text(text: str) -> dict:
    """Analyze a text string and return basic validation statistics."""
    stripped = text.strip()
    if not stripped:
        return {
            "valid": False,
            "reason": "Text is empty or only whitespace",
            "characters": 0,
            "words": 0,
    …
11 0 Open
Strings & text easy

How to Validate Text Strings in Python

Validate strings with a reusable helper that checks type, length limits, and empty string handling.

validation strings helper-function
Python
def is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
    """
    Validate if a value is a string and meets length requirements.
    
    Args:
        value: The value to validate
        min_length: Minimum allowed length (default 1)
        max_length: Maximum allowed length (None = no limit)
…
13 0 Open
Strings & text easy

Validate email format with regex in Python

A Python function using a regex pattern to validate simple email formats, returning True or False for each input.

regex email validation
Python
import re

def is_valid_email(email):
    pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
    return bool(re.match(pattern, email))

if __name__ == "__main__":
    test_emails = [
        "user@example.com",
        "first.last@sub.domain.org",
        "invalid-email",
        "user@.com",
        "user@…
12 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…
45 0 Open
Lists & loops easy

How to Validate List Data in Python

A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.

validation lists loops
Python
def validate_data(data, expected_types=None, min_length=1):
    """Validate that data is a non-empty list and optionally check item types."""
    if not isinstance(data, list):
        return False, f"Expected a list, got {type(data).__name__}"
    
    if len(data) < min_length:
        return False, f"List must have…
16 0 Open
Lists & loops easy

How to Validate Text Against Forbidden Words in Python

Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.

text validation lists loops
Python
def validate_text(text, forbidden_words):
    """
    Checks that text does not contain any forbidden words.
    Returns (is_valid, offending_words) tuple.
    """
    words = text.lower().split()
    found = [word for word in words if word in forbidden_words]
    return len(found) == 0, found


if __name__ == "__main…
14 0 Open
Functions & basics easy

Build a Progress Callback Function for Loops in Python

Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.

callback loops progress
Python
def run_with_progress(items, desc="Processing", step_callback=None):
    """Run a loop with progress updates via callback."""
    total = len(items)
    for idx, item in enumerate(items):
        # Process the item (simulated work here)
        result = item * 2

        # Build progress data dictionary
        if ste…
14 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…
46 0 Open
Functions & basics easy

How to Validate CLI Integer Option Within a Range in Python

Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.

argparse cli validation
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Validate an integer within a range.")
    parser.add_argument("--value", type=int, required=True, help="Integer to validate")
    parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
    parser.add_argument("--max…
13 0 Open
Functions & basics easy

How to Validate Function Arguments in Python

Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.

validation function arguments type hints
Python
def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle with manual type validation."""
    if not isinstance(length, (int, float)) or isinstance(length, bool):
        raise TypeError(f"length must be a number, got {type(length).__name__}")
    if not isinstance(width, (int,…
13 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}")
16 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 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

How to Validate JSON in Python and Catch JSONDecodeError

A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.

json validation jsondecodeerror
Python
import json

def validate_json(json_string):
    """Try to parse JSON, return (is_valid, data_or_error)."""
    try:
        data = json.loads(json_string)
        return True, data
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

if __name__ == "__main__":
    test_inputs = [
        …
11 0 Open
Errors & debugging easy

How to Validate an Email Address and Raise ValueError in Python

This code defines a validate_email function that checks an email address against a regex pattern and several rules, raising ValueError with a specific reason when invalid.

validation regex errors
Python
import re

def validate_email(email: str) -> str:
    """Validate an email address and return it if valid, otherwise raise ValueError."""
    if not isinstance(email, str):
        raise ValueError("Email must be a string")
    if len(email) > 254:
        raise ValueError("Email length exceeds 254 characters")

    #…
14 0 Open
Errors & debugging easy

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.

none error-handling validation
Python
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__ == "__…
15 0 Open
Errors & debugging easy

Validate try except ValueError handler for beginners — errors debugging

Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.

try except valueerror
Python
def divide_numbers(a, b):
    """Divide two numbers, catching division by zero and value errors."""
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        return None
    except TypeError:
        print("Error: Both arguments must be numbers!")
        retu…
14 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…
48 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 Validate JSON Schema Shape in Python

Validate JSON data against a schema using manual checks for required fields, types, and constraints.

json validation schema
Python
import json
from typing import Any, Dict

def validate_person_schema(data: Dict[str, Any]) -> bool:
    """Validate a person object against expected schema shape."""
    if not isinstance(data, dict):
        return False
    
    # Required fields check
    required_fields = {"name", "age", "email"}
    if not requir…
12 0 Open
Files & data easy

How to Validate a JSON File in Python

A beginner-friendly Python helper that reads a JSON file, catches common errors, and returns a status dictionary.

json validation file-handling
Python
import json
from pathlib import Path

def get_valid_json_data(file_path: str) -> dict:
    file = Path(file_path)
    if not file.exists():
        return {"status": "error", "message": f"File not found: {file_path}"}
    
    try:
        data = json.loads(file.read_text())
    except json.JSONDecodeError as e:
     …
12 0 Open
Files & data easy

Normalize CSV Column Names to snake_case in Python

Convert CSV header names to snake_case using a regular expression and write the updated file in place.

csv regex snake-case
Python
import csv
import re
import sys


def to_snake_case(header):
    header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
    header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
    return header


def normalize_csv_headers(input_path, output_path=None):
    with open(input_path, newline="", encoding="utf…
13 0 Open
Dictionaries & sets easy

Build an OrderedDict insertion order demo in Python 3

Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.

ordereddict dictionaries insertion-order
Python
from collections import OrderedDict

def demo_ordered_dict():
    # Create an OrderedDict and insert items in a specific order
    ordered = OrderedDict()
    ordered['banana'] = 3
    ordered['apple'] = 2
    ordered['cherry'] = 5
    ordered['date'] = 1

    print("Insertion order preserved:")
    for key, value in …
13 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.