Reference library

Python Code Samples

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

6 matches
A/B testing & experimentation medium

How to Compute CUPED Variance Reduction in Python

Implement CUPED in Python to reduce variance of A/B test treatment effect estimates using pre-experiment covariates.

cuped ab-testing variance-reduction
Python
import numpy as np

def compute_cuped_reduction(control, variant, covariate):
    """
    Compute variance reduction using CUPED (Controlled Experiment with
    Pre-Experiment Data). Uses pre-experiment covariate values to
    reduce variance of the treatment effect estimate.
    """
    control = np.asarray(control, …
16 0 Open
A/B testing & experimentation medium

How to Generate an Orthogonal Array for A/B Testing in Python

Generate a mock orthogonal array for multi-layer experiments with NumPy, ensuring balanced level combinations across experiment groups.

ab-testing orthogonal-array numpy
Python
import numpy as np

def orthogonal_mock_layers(n_experiments: int, n_layers: int, n_levels: int) -> np.ndarray:
    """Generate an orthogonal array for multi-layer experiment design using base-level logic."""
    ortho = np.indices((n_levels,) * n_layers).reshape(n_layers, -1).T
    ortho = ortho % n_levels  # Classic…
14 0 Open
A/B testing & experimentation easy

How to Hash a User ID to an Experiment Bucket in Python

Deterministically map a user ID to one of N experiment buckets using MD5 hashing and modulo arithmetic.

hashing ab-testing bucketing
Python
import hashlib

def hash_to_bucket(user_id: str, num_buckets: int = 10) -> int:
    """Deterministically map a user_id to a bucket (0 to num_buckets-1)."""
    digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
    return int(digest[:8], 16) % num_buckets

if __name__ == "__main__":
    # Mock experiment: split…
14 0 Open
A/B testing & experimentation easy

How to Mock Stratified Assignment by Segment in Python

Simulate stratified assignment for A/B experiments by sampling a fixed proportion of units from each segment, with deterministic seeds for reproducibility.

ab-testing sampling random
Python
import random

def stratified_assignment(segments, seed=None):
    """
    Mock stratified assignment: given a dict of segment -> population size,
    return a dict of segment -> sampled unit ids (deterministic with seed).
    """
    if seed is not None:
        random.seed(seed)
    rng = random.Random(seed)
    res…
12 0 Open
A/B testing & experimentation medium

How to Simulate Geo Experiments in Python

Build a mock geo experiment simulator with ramp-up/down periods, measuring weekly lift between treatment and control markets.

geo-experiment ab-testing simulation
Python
import random
import math
from dataclasses import dataclass

@dataclass
class GeoMarket:
    name: str
    base_demand: float
    geo_coefficient: float

def simulate_geo_experiment(markets, weeks=12, control_weeks=6):
    """
    Simulates a geo experiment with ramp-up and ramp-down periods.
    Returns weekly lift p…
18 0 Open
A/B testing & experimentation easy

How to hash user IDs to experiment buckets in Python

Deterministically map a user ID to an experiment bucket using MD5 hashing, ensuring stable and consistent assignment for A/B testing.

hashing ab-testing experiments
Python
import hashlib


def hash_user_to_bucket(user_id: str, num_buckets: int = 10) -> int:
    """Deterministically map a user ID to an experiment bucket (0..num_buckets-1)."""
    digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
    return int(digest, 16) % num_buckets


if __name__ == "__main__":
    mock_users …
12 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.