Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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")
#…
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.
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__ == "__…
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.
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")…
Automatically Detect Corrupted Files Using SHA-256 Checksums in Python
Compute SHA-256 checksums of files and compare them to detect corruption in 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…
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.
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"…
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.
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…
How to Validate JSON Schema Shape in Python
Validate JSON data against a schema using manual checks for required fields, types, and constraints.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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",
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
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…
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 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)
…
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.
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
…
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.
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…
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.
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…
Implement Queue Using Two Stacks in Python
Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.
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())
…
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.
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…
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.
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,…
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.
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 {
…
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.
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 …
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.
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…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.