Reference library

Python Code Samples

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

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

Python dict try-except KeyError EAFP vs LBYL

Compare EAFP (try-except) and LBYL (if-in-check) styles for safely accessing dictionary keys, with working examples in Python.

eafp lbyl dictionary
Python
def safe_get_lbyl(d, key):
    if key in d:
        return d[key]
    return "default-lbyl"

def safe_get_eafp(d, key):
    try:
        return d[key]
    except KeyError:
        return "default-eafp"

if __name__ == "__main__":
    data = {"name": "Alice", "age": 30}
    print("LBYL:", safe_get_lbyl(data, "missing")…
14 0 Open
Files & data easy

Automatically Detect Corrupted Files Using SHA-256 Checksums in Python

Compute SHA-256 checksums of files and compare them to detect corruption in Python.

checksum file-integrity hashlib
Python
import hashlib
import os

def compute_sha256(filepath: str) -> str:
    """Compute SHA-256 checksum of a file."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdigest()

def validate_file_int…
57 1 Open
Files & data easy

How to Check Disk Free Space in Python with shutil.disk_usage

This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.

shutil disk usage disk space
Python
import shutil


def check_disk_free_space(path="/"):
    """Return a tuple of total, used, and free disk space in bytes."""
    usage = shutil.disk_usage(path)
    return usage.total, usage.used, usage.free


if __name__ == "__main__":
    total, used, free = check_disk_free_space()
    print(f"Total: {total:,} bytes"…
12 0 Open
Files & data easy

How to Delete a File if it Exists in Python

Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.

pathlib file-deletion file-management
Python
from pathlib import Path

def delete_file_if_exists(file_path: str) -> bool:
    """Delete a file if it exists. Returns True if deleted, False if not found."""
    path = Path(file_path)
    if path.exists():
        path.unlink()
        print(f"Deleted: {path}")
        return True
    else:
        print(f"File not…
14 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 check file data in Python

Check if a file exists and is a regular file, then return its name, size, line count, and first line.

file pathlib metadata
Python
def check_file_data(file_path):
    from pathlib import Path
    path = Path(file_path)
    if not path.exists():
        return f"File '{file_path}' does not exist."
    if not path.is_file():
        return f"'{file_path}' is not a regular file."
    
    size = path.stat().st_size
    lines = path.read_text(encodin…
15 0 Open
Dictionaries & sets easy

Check Invertible Mapping for Duplicate Values in Python

Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.

dictionary mapping duplicate-check
Python
def invertible_after_dedup(pairs):
    """
    Check whether a set of (key, value) pairs is invertible,
    i.e., no duplicate values exist for different keys.
    """
    seen = {}
    for key, value in pairs:
        if value in seen and seen[value] != key:
            return False, f"Duplicate value '{value}' for k…
16 0 Open
Dictionaries & sets easy

How to Check Data Type and Inspect Dictionaries and Sets in Python

Inspect dictionaries and sets by printing their contents, types, and sizes using a small helper function.

dictionaries sets isinstance
Python
def check_data(data):
    """Helper to inspect dictionaries and sets."""
    if isinstance(data, dict):
        print(f"Dictionary with {len(data)} keys")
        for key, value in data.items():
            print(f"  {key}: {value} ({type(value).__name__})")
    elif isinstance(data, set):
        print(f"Set with {le…
13 0 Open
Dictionaries & sets easy

How to Check if a Set is a Subset in Python

Check whether one set contains all elements of another set using the issubset method.

set subset membership
Python
def is_subset(allowed_set, check_set):
    """
    Check if check_set is a subset of allowed_set.
    Returns True if all elements of check_set are in allowed_set, otherwise False.
    """
    return check_set.issubset(allowed_set)

if __name__ == "__main__":
    # Example usage
    allowed = {1, 2, 3, 4, 5}
    valid…
17 0 Open
Dictionaries & sets medium

How to Implement Disjoint Set Union Find in Python

Implement a Disjoint Set Union-Find data structure using a Python dictionary for parent tracking, with path compression and connectivity checks.

disjoint-set union-find graph
Python
class DisjointSet:
    def __init__(self):
        self.parent = {}

    def find(self, x):
        # Path compression
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        # Initialize if not present
        if x not in…
13 0 Open
Dictionaries & sets easy

How to Validate Required Dict Keys in Python

Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.

dictionary validation missing-keys
Python
def find_missing_keys(data: dict, required_keys: list) -> list:
    """Return a list of required keys that are missing from the dictionary."""
    return [key for key in required_keys if key not in data]


if __name__ == "__main__":
    user_data = {
        "name": "Alice",
        "email": "alice@example.com",
     …
12 0 Open
OOP & classes medium

Composable Predicates with the &, |, ~ Operators in Python

Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.

predicates operator-overloading oop
Python
class Predicate:
    def __init__(self, func, name=None):
        self.func = func
        self.name = name or getattr(func, "__name__", "predicate")

    def __call__(self, value):
        return self.func(value)

    def __and__(self, other):
        return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
13 0 Open
OOP & classes easy

How to Validate Data Types in Python with a Class

A beginner-friendly Python class that checks if a value is a string, integer, float, list, or empty, using simple methods and isinstance checks.

class validation type checking
Python
class DataValidator:
    """A simple data validation helper for beginners."""
    
    def __init__(self, data):
        self.data = data
    
    def is_string(self):
        return isinstance(self.data, str)
    
    def is_integer(self):
        return isinstance(self.data, int) and not isinstance(self.data, bool)
…
13 0 Open
OOP & classes easy

How to Validate User Input with a Dataclass in Python

A dataclass stores name, age, and email, and a validator class checks each field, returning a dictionary of boolean results.

dataclass validation oop
Python
from dataclasses import dataclass


@dataclass
class UserInput:
    name: str
    age: int
    email: str

    def is_valid_name(self) -> bool:
        return bool(self.name.strip()) and len(self.name.strip()) >= 2

    def is_valid_age(self) -> bool:
        return isinstance(self.age, int) and 0 < self.age < 150

  …
15 0 Open
OOP & classes easy

Validate dataclass fields with __post_init__ in Python

Add custom validation to a Python dataclass inside __post_init__, raising ValueError or TypeError for invalid field values.

dataclasses validation post-init
Python
from dataclasses import dataclass, field
from typing import Optional


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1
    category: Optional[str] = None

    def __post_init__(self):
        if not self.name or not isinstance(self.name, str):
            raise ValueError("name must be a…
11 0 Open
Algorithms & data structures easy

How to Remove Duplicates in Python Preserving Order

Removes duplicate items from a list while keeping the first occurrence order intact using a set for fast membership checks.

deduplication set list
Python
def remove_duplicates_preserving_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

if __name__ == "__main__":
    sample = [3, 1, 2, 1, 3, 4, 2, 5]
    unique_items = remove_duplicates_preserv…
14 0 Open
Algorithms & data structures easy

Implement Queue Using Two Stacks in Python

Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.

queue stack data-structures
Python
class QueueUsingStacks:
    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def enqueue(self, value):
        self.stack_in.append(value)

    def dequeue(self):
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
  …
13 0 Open
Algorithms & data structures medium

Split Array Largest Sum in Python (Minimize Largest Subarray Sum)

Binary search + greedy check to split an array into k subarrays while minimizing the largest subarray sum.

binary-search greedy array
Python
def can_split(nums, k, max_sum):
    subarrays = 1
    current_sum = 0
    for num in nums:
        if current_sum + num <= max_sum:
            current_sum += num
        else:
            subarrays += 1
            current_sum = num
            if subarrays > k:
                return False
    return True

def spli…
15 0 Open
Algorithms & data structures medium

Validate Sudoku Board Rows Columns and Boxes in Python

Validate a 9x9 Sudoku board by checking that each row, column, and 3x3 box contains the numbers 1 through 9 exactly once.

sudoku validation matrix
Python
def validate_sudoku(board):
    def is_valid_group(group):
        return sorted(group) == list(range(1, 10))

    def get_columns():
        return [[board[r][c] for r in range(9)] for c in range(9)]

    def get_boxes():
        boxes = []
        for box_row in range(0, 9, 3):
            for box_col in range(0, 9,…
11 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators to Check Data in Python

A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.

comprehensions generators data-checking
Python
def check_data(iterable):
    """Return a summary of numeric data using comprehensions and a generator."""
    values = [item for item in iterable if isinstance(item, (int, float))]
    squares = [x ** 2 for x in values if x > 0]
    cubes = (x ** 3 for x in values if x > 0)
    cube_list = list(cubes)
    return {
  …
13 0 Open
AI & LLM integration patterns easy

How to Validate JSON Output Against a Dict Schema in Python

Validate JSON-like data against a simple dict schema with type checking and descriptive error messages using only the Python standard library.

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

def validate_json(data: Any, schema: Dict[str, str]) -> List[str]:
    """
    Validate JSON-like data against a simple dict schema.
    Schema format: {field_name: expected_type} where type is one of:
    'str', 'int', 'float', 'bool', 'list', 'dict', 'any'
    Returns list …
13 0 Open
AI & LLM integration patterns easy

How to Validate LLM Output in Python

A beginner-friendly DataValidator class that checks required fields and type constraints on LLM-generated or user JSON data.

validation llm json
Python
import json
from typing import Any, Dict, List, Optional


class DataValidator:
    """Simple helper for validating LLM-generated or user data."""

    def __init__(self, required_fields: List[str], schema: Optional[Dict[str, str]] = None):
        self.required_fields = required_fields
        self.schema = schema or…
14 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.