Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, r…
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.
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 = [
…
How to Convert CSV Column Types While Reading in Python
Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.
import csv
from pathlib import Path
from typing import Any
def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
"""Read CSV and convert column types based on header suffixes."""
converters = {
"int": int,
"float": float,
"str": str,
"bool": lambda v: v.strip().lower(…
Parse Env Vars into Typed Dict in Python
Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.
import os
from typing import Any, Dict
def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
"""Parse a list of environment variable names into a typed dict.
Each variable is parsed as:
- bool: "true"/"false" (case-insensitive)
- int: if it can be converted t…
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 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
…
How to Compare Two Lists Elementwise for Greater Flags in Python
Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.
def compare_lists_greater(list_a, list_b):
"""
Compare two lists elementwise and return a list of booleans
indicating whether each element in list_a is greater than the
corresponding element in list_b.
"""
if len(list_a) != len(list_b):
raise ValueError("Lists must have the same length"…
Set Matrix Zeroes in Python: Markers List Grid Demo
Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.
def set_zeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_markers = [False] * rows
col_markers = [False] * cols
# First pass: record which rows and columns contain zeros
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_markers[i] …
How to Compress a Generator with a Boolean Mask in Python
Filters items from a generator based on a parallel boolean mask, yielding only the items where the mask is True.
def compress(generator, mask):
for item, keep in zip(generator, mask):
if keep:
yield item
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
mask = [True, False, True, False, True]
result = list(compress(iter(data), mask))
print(result)
How to Convert Data Types in a Python Data Pipeline
Demonstrates a simple Python data pipeline that converts string values to proper types (bool, int, float, datetime) and outputs structured JSON.
import json
from datetime import datetime
def convert_value(value):
"""Convert string values to appropriate Python types."""
if value.lower() == "true":
return True
if value.lower() == "false":
return False
if value.isdigit():
return int(value)
try:
return float(val…
How to Validate Data with a Simple Dict-Based Rules Helper in Python
Validates a dictionary against a set of callable rules, printing pass/fail per field and returning an overall boolean.
import json
from pathlib import Path
from typing import Any, Callable
def validate_data(
data: dict[str, Any],
rules: dict[str, Callable[[Any], bool]],
path: Path | None = None,
) -> bool:
"""Validate a dict against a set of simple rules."""
all_valid = True
for field, validator in rules.item…
How to Convert Strings to Types in Python Using TypeVar
A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.
from typing import TypeVar, Optional
T = TypeVar("T")
def convert_data(value: str, target_type: type[T]) -> Optional[T]:
"""Convert string value to target type; return None on failure."""
try:
if target_type is int:
return int(value)
elif target_type is float:
return f…
How to Use Mock Flip Mutation Testing in Python
Demonstrates how mutation testing tools flip Boolean literals (mock flip) in Python source to verify test suite effectiveness in catching logic changes.
import random
# In mutation testing, a "mock flip" intentionally changes a Boolean
# constant to False (or True) to see if the test suite catches it.
# This is a common "constant mutation" applied to a source file's literals.
def is_even(n: int) -> bool:
"""Return True if n is even. Contains a Boolean literal us…
How to Evaluate Feature Flags in Python
A Python function that evaluates boolean feature flags with user-specific overrides, returning whether a flag is enabled and the reason for the decision.
import json
def evaluate_feature_flag(feature_name, context, flag_configs):
"""
Evaluates a boolean feature flag given a context dictionary.
Args:
feature_name: The name of the feature flag.
context: A dictionary of user/request context (e.g., {"user_id": "123"}).
flag_configs: A …
How to Generate Multivariate JSON Mock Data in Python
This script generates mock multivariate JSON-compatible data with measurements and boolean flags for testing and experimentation pipelines.
import json
def multivariate_mock(row_count: int = 3) -> list:
"""Generate mock multivariate data as list of JSON-compatible dicts."""
records = []
for i in range(row_count):
record = {
"id": i + 1,
"measurements": {
"temperature": 20.5 + i * 1.5,
…
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.