Reference library

Python Code Samples

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

58 matches
A/B testing & experimentation easy

How to create a global control holdout group in Python

This code implements a deterministic global control holdout group, randomly selecting a fraction of users to be excluded from feature rollouts for experiment validation.

ab-testing holdout global-control
Python
import random

class GlobalControl:
    def __init__(self, population_size, holdout_fraction=0.2, seed=42):
        random.seed(seed)
        self.population_size = population_size
        self.holdout_fraction = holdout_fraction
        self.holdout_size = int(population_size * holdout_fraction)
        self.holdout_…
11 0 Open
A/B testing & experimentation medium

How to simulate a contextual bandit in Python

Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.

bandit-algorithms simulation epsilon-greedy
Python
import random


class ContextualBandit:
    def __init__(self, n_actions=3, n_features=4):
        self.n_actions = n_actions
        self.n_features = n_features
        self.theta = [random.random() for _ in range(n_actions * n_features)]

    def mock_context(self):
        return [random.uniform(-1, 1) for _ in ra…
13 0 Open
A/B testing & experimentation easy

Simulate a Ramp Rollout Percentage in Python

Simulates a percentage-based ramp rollout with deterministic seeding, returning success/failure/in-progress counts for a mock user population.

rollout simulation random
Python
import random
from enum import Enum

class RolloutStatus(Enum):
    SUCCESS = "success"
    FAILED = "failed"
    IN_PROGRESS = "in_progress"

def simulate_ramp_rollout(total_users: int, percentage: int, seed: int = 42) -> dict:
    """
    Simulates a mock ramp rollout for a given percentage of users.
    Returns sta…
14 0 Open
Database scaling & optimization easy

Monitor Database Index Bloat in Python

Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.

database index monitoring
Python
import random
import time

class IndexBloatMonitor:
    def __init__(self, thresholds=(0.5, 0.8, 0.9)):
        self.thresholds = thresholds
        self.indices = {
            "users_pk": 48.2,
            "orders_created_idx": 124.7,
            "products_name_idx": 15.3,
            "payments_user_idx": 203.9,
   …
15 0 Open
Auth & security at scale easy

How to Hash Passwords Securely in Python

Hash passwords with PBKDF2, random salts, and constant pepper, plus generate secure API keys using Python's stdlib.

password hashing security
Python
import hashlib
import secrets
import time
import hmac


def hash_password(password: str, salt: str = None, pepper: str = "static-pepper") -> dict:
    """Hash a password with a random salt and constant pepper."""
    if salt is None:
        salt = secrets.token_hex(16)
    salted = f"{pepper}{salt}{password}"
    dig…
15 0 Open
Auth & security at scale easy

How to Hash Passwords with bcrypt in Python

Hash a plaintext password with bcrypt using a randomly generated salt, then verify a plaintext attempt against the stored hash.

bcrypt password security
Python
import bcrypt

def hash_password(password: str) -> str:
    """Hash a password using bcrypt with a generated salt."""
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")

def check_password(password: str, hashed: str) -> bool:
    """Verify a plaintext password against …
13 0 Open
Auth & security at scale easy

How to Salt Passwords per User in Python

Hash each user's password with a unique random salt using hashlib, and verify logins with timing-safe comparison.

password-hashing security authentication
Python
import hashlib
import secrets

def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
    """Hash a password with a random salt (or provided salt).

    Returns:
        (salt_hex, password_hash_hex)
    """
    if salt is None:
        salt = secrets.token_hex(16)
    salted = (salt + password)…
14 0 Open
Production deployment patterns medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
13 0 Open
Production deployment patterns easy

How to Implement a Manual Approval Gate Mock in Python

Simulates a manual approval workflow with threshold-based rules, random decisions for medium amounts, and logs each result with timing.

approval simulation workflow
Python
import random
import time


def approve_request(amount: float) -> bool:
    if amount <= 1000:
        return True
    if amount <= 5000:
        return random.random() < 0.7
    return False


def main():
    requests = [500, 1200, 7500, 3000, 50]
    for amount in requests:
        start = time.perf_counter()
      …
18 0 Open
Production deployment patterns easy

How to Mock a CI Pipeline with Build, Test, and Deploy Stages in Python

Simulate a three-stage CI pipeline (build, test, deploy) in Python with random pass/fail logic, early exit on failure, and measured stage durations.

ci-cd simulation dataclasses
Python
import time
import random
from dataclasses import dataclass


@dataclass
class StageResult:
    name: str
    status: str
    duration: float


def run_stage(name: str, success_chance: float = 0.9) -> StageResult:
    """Simulate a pipeline stage with random success/failure."""
    start = time.time()
    time.sleep(r…
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.