Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Download Files from Internet with Progress Bar in Python
Download a file from the internet while displaying a text progress bar in the terminal.
import urllib.request
import sys
def download_with_progress(url, filename):
"""Download a file with a simple text progress bar."""
def report_hook(block_count, block_size, total_size):
downloaded = block_count * block_size
if total_size > 0:
percent = min(100, int(downloaded * 100 …
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
How to Detect Network Interface Changes in Python
Monitor active network interfaces and print a message when an interface is added or removed using psutil and socket.
import socket
import psutil
import time
def get_network_interfaces():
"""Return a set of currently active interface names."""
active_ifaces = set()
for iface, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == socket.AF_INET: # IPv4 address present
…
How to Ping Multiple Hosts in Parallel with Python ThreadPoolExecutor
A parallel host-pinging script using ThreadPoolExecutor and subprocess to check connectivity across multiple addresses concurrently.
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HOSTS = [
"google.com",
"github.com",
"stackoverflow.com",
"nonexistent.invalid",
"localhost",
]
def ping_host(host: str) -> str:
"""Ping a single host and return a status string."""
result = subp…
How to Scan Open Ports on a Host with Python
A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.
import socket
def scan_ports(host, start_port, end_port):
open_ports = []
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
if result == 0:
open_ports.app…
How to Validate SSL Certificates for Multiple Domains in Python
A Python utility that checks SSL certificate expiry dates for a list of domains using the standard library ssl and socket modules.
import ssl
import socket
from datetime import datetime
def check_ssl_certificate(hostname: str, port: int = 443) -> dict:
"""Validate SSL certificate for a given hostname."""
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wra…
How to Mock asyncio.open_connection in Python
Mock asyncio.open_connection with AsyncMock to test async code without a real network connection.
import asyncio
from unittest.mock import AsyncMock, patch
async def fetch_data(reader: asyncio.StreamReader) -> str:
data = await reader.readline()
return data.decode().strip()
async def main() -> None:
# Mock asyncio.open_connection to simulate a server response
mock_reader = AsyncMock()
mock_…
How to Implement Retry with Exponential Backoff and Jitter in Python
This code demonstrates a retry mechanism with exponential backoff and optional full jitter, using a flaky mock network call for testing.
import random
import time
def retry_with_backoff(func, max_attempts=5, base_delay=0.1, jitter=True):
"""
Retry a function with exponential backoff and optional full jitter.
"""
for attempt in range(max_attempts):
try:
return func()
except Exception as e:
if att…
GCRA generic cell rate algorithm in Python
Mock implementation of the Generic Cell Rate Algorithm (GCRA) for traffic shaping and rate limiting.
from collections import deque
import time
class GCRA:
def __init__(self, rate, burst):
self.tau = burst
self.T = rate
self.t = 0
self.LCT = 0
def add_cell(self, arrival_time):
if arrival_time <= self.t:
return False
arrived_early = (arrival_time - s…
Leaky Bucket Rate Limiter in Python: Smooth Burst Traffic
Implements a token-bucket-style leaky bucket rate limiter that smooths bursty traffic by draining at a fixed rate and dropping excess packets.
import time
import random
class LeakyBucket:
def __init__(self, capacity, drain_rate):
self.capacity = capacity
self.drain_rate = drain_rate
self.water = 0.0
self.last_time = time.time()
def allow(self, packet_size=1.0):
now = time.time()
elapsed = now - self.…
How to Simulate a MapReduce Mock with Combine Phase in Python
Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.
from collections import defaultdict
def map_phase(lines):
intermediate = defaultdict(list)
for line in lines:
for word in line.strip().lower().split():
intermediate[word].append(1)
return dict(intermediate)
def combine_phase(intermediate, num_reducers=3):
combined = defaultdict(li…
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.