Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Implement a Weighted DNS Resolver with Failover in Python
Simulates a weighted DNS load balancer that distributes traffic across IPs by weight and automatically fails over when a server is marked unhealthy.
import random
import time
class WeightedDNSResolver:
def __init__(self, records):
self.records = records # list of (ip, weight)
self.total_weight = sum(weight for _, weight in records)
self.failed_ips = set()
def resolve(self):
available = [(ip, weight) for ip, weight in self…
How to Build a Weighted Random Load Balancer in Python
A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.
import random
from collections import Counter
SERVERS = {
"server-a": 50,
"server-b": 30,
"server-c": 20,
}
def weighted_random_server(servers: dict[str, int]) -> str:
"""Select a server based on its weight (higher weight = more likely)."""
total_weight = sum(servers.values())
rand = random.…
How to Calculate Weighted Grades and Generate Mock Notes in Python
Compute a weighted physics grade from exam and homework scores, then generate a performance-based mock note with percentage and feedback.
def get_physics_grade(exam_score, homework_score):
"""Calculate final grade from exam and homework scores."""
exam_weight = 0.7
homework_weight = 0.3
return (exam_score * exam_weight) + (homework_score * homework_weight)
def mock_note(correct_score, max_score, student_name):
"""Generate a mock no…
How to Do Random Assignment in Python for A/B Tests
Assign each item to a binary group (0 or 1) with uniform probability using a small reusable function, optionally weighted, for A/B testing mocks.
import random
def random_assignment_uniform_mock(items, weights=None):
"""Assign each item to a group (0 or 1) with uniform probability."""
if weights is None:
# Default: each item independently gets 0 or 1 with 50% probability
return [random.randint(0, 1) for _ in items]
# Optional weight…
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.