Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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_…
How to simulate a contextual bandit in Python
Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in 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…
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.
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…
Monitor Database Index Bloat in Python
Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.
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,
…
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.
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…
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.
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 …
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.
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)…
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.
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…
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.
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()
…
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.
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…
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.