Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Check if a String is Alphanumeric in Python
Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.
def is_alphanumeric(s: str) -> bool:
return s.isalnum()
if __name__ == "__main__":
test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
for case in test_cases:
result = is_alphanumeric(case)
print(f"{case!r:15} -> {result}")
How to Detect if a String Contains Only ASCII in Python
This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.
def is_ascii_only(text: str) -> bool:
"""Return True if all characters in text are ASCII, False otherwise."""
return all(ord(char) < 128 for char in text)
if __name__ == "__main__":
# Test cases
samples = [
"Hello, world!",
"Café au lait",
"日本語テキスト",
"ASCII only 123",
…
Python String isalpha() Method: Check if String is Alphabetic
This code defines a function that uses Python's str.isalpha() method to determine if a string contains only alphabetic characters, with a demonstration on several test strings.
def is_alphabetic(s):
return s.isalpha()
if __name__ == "__main__":
test_strings = ["Hello", "Hello123", "World!", "Python", ""]
for s in test_strings:
print(f"{s!r}: {is_alphabetic(s)}")
Find Duplicate Elements in a Python List
Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
if __name__ == "__main__":
sample = [1, 2, 3, 2, 4, 1, 5, 3]
print(find_duplicates(sample))
How to Mock a Failing Dependency to Test Error Paths in Python
Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.
import requests
def fetch_user(user_id):
url = f"https://api.example.com/users/{user_id}"
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
def get_user_name(user_id, http_client):
try:
user_data = http_client(user_id)
return user_data["nam…
How to Test Exceptions in Python with pytest.raises
Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.
import pytest
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero_raises():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
def test_divide_by_zero_raises_exact_match():
with py…
How to filter a generator with a predicate function in Python
This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.
def filter_gen(predicate, iterable):
for item in iterable:
if predicate(item):
yield item
def is_even(num):
return num % 2 == 0
def is_positive(num):
return num > 0
if __name__ == "__main__":
numbers = range(-5, 10)
even_numbers = list(filter_gen(is_even, numbers))
p…
How to Create a Mock Text Embedding with Hash in Python
Generate deterministic mock text embeddings using SHA-256 hashing and numpy, producing normalized vectors for similarity testing without an LLM.
import hashlib
import numpy as np
def mock_embed(text: str, dim: int = 10, seed: int = 42) -> np.ndarray:
"""Generate a deterministic mock embedding using a hash function.
Args:
text: Input text to embed
dim: Dimension of the output vector
seed: Seed for reproducibility
R…
How to Mock OpenAI Tool Call Messages in Python
Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.
from openai import OpenAI
def mock_tool_call(tool_name: str, arguments: dict) -> dict:
"""Simulate a tool call message in OpenAI style."""
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_" + "a1b2c3d4e5f6",
"type…
How to Mock an LLM Client in Python
Create a simple mock LLM client that returns a canned completion for testing or development without a real API.
from dataclasses import dataclass
@dataclass
class MockLLMClient:
canned_response: str = "This is a canned completion."
def complete(self, prompt: str) -> str:
return f"{self.canned_response} [to: {prompt[:20]}]"
if __name__ == "__main__":
client = MockLLMClient()
result = client.complete(…
How to Stream Tokens from a Mock LLM in Python
Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.
import time
from typing import Generator
def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
"""Simulate an LLM streaming tokens word by word."""
for word in text.split():
yield word
time.sleep(delay)
if __name__ == "__main__":
sample = "Hello world! This is…
How to randomly assign a prompt variant to each key in Python
Randomly pick one variant from a list for each prompt key, useful for A/B testing message variations.
import random
def assign_prompt_variant(prompts: dict[str, list[str]]) -> dict[str, str]:
"""Assign a random prompt variant to each prompt key."""
return {key: random.choice(variants) for key, variants in prompts.items()}
if __name__ == "__main__":
prompt_bank = {
"greeting": ["Hello!", "Hi there…
Automatically Download the Latest Software Release from GitHub with Python
Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.
import requests
import sys
from pathlib import Path
def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
"""Download the latest release asset from a GitHub repository."""
url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
response = requests.get(url)
res…
Create Mock Watermarked Image Bytes in Python Without PIL
Builds a mock image-like byte stream with an embedded watermark using only stdlib modules, for testing pipelines without PIL.
from io import BytesIO
import zlib
import struct
def create_watermarked_bytes(width: int, height: int, watermark: bytes) -> bytes:
"""Create a mock image-like byte stream with a watermark (no PIL)."""
header = struct.pack("<2I", width, height)
payload = watermark * max(1, (width * height // max(1, len(wa…
Generate Random Fake User Data for Testing in Python
This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.
import json
import random
import string
from datetime import datetime, timedelta
def generate_user_data(num_users=1):
first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
domains = ["example.com", "test.org", "demo.net"]
users = …
How to Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
How to Download All Assets from GitHub Releases in Python
Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.
import requests
import os
import zipfile
from pathlib import Path
def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
"""Downloads all assets from the latest release of a GitHub repository."""
releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
How to Mock FFmpeg subprocess Calls in Python
Compress a video with ffmpeg while mocking subprocess.run to test the command construction without executing the actual encoder.
import subprocess
from unittest.mock import Mock, patch
def compress_video(input_path: str, output_path: str, crf: int = 23) -> None:
"""Compress a video using ffmpeg with a given CRF (quality) value."""
command = [
"ffmpeg",
"-i", input_path,
"-c:v", "libx264",
"-crf", str(cr…
How to Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
How to Send an Email with smtplib and a Mock Server in Python
Send an email using smtplib and verify it with a local aiosmtpd mock SMTP server — perfect for testing without a real mail server.
import smtplib
from email.message import EmailMessage
import aiosmtpd.controller as controller
import threading
def handle_message(server, session, envelope):
print(f"Mock server received message:")
print(f"From: {envelope.mail_from}")
print(f"To: {envelope.rcpt_tos}")
print(f"Subject: {envelope.cont…
How to Simulate a Traceroute in Python
This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.
import random
import time
def simulate_traceroute(destination, max_hops=30):
"""Simulate a traceroute to a destination with mock hop delays."""
print(f"Traceroute to {destination} ({max_hops} hops max):")
for hop in range(1, max_hops + 1):
# Mock IP address for the hop
mock_ip = f"10.0.{ra…
How to Strip EXIF Metadata from Images in Python
Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct
def strip_exif(image_bytes, remove_metadata=True):
"""Remove EXIF metadata from image bytes."""
img = Image.open(BytesIO(image_bytes))
if remove_metadata:
# Clear all metadata
img.info.clear()
# Sa…
Mock Certbot Renewal in Python for Testing
Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
def renew_cert(domain: str, output_dir: str = "certs") -> str:
"""Simulate a Let's Encrypt renewal with mock certbot output."""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
cert_path = out…
Mock a Helm Upgrade Install Command in Python
Use unittest mock to simulate a Helm upgrade --install call for testing automation scripts without a real cluster.
from unittest.mock import MagicMock, patch
class HelmClient:
def upgrade_install(self, release, chart, namespace="default"):
# Simulates the helm upgrade --install command
return f"Release {release} upgraded/installed in {namespace} using chart {chart}"
@patch("helm_client.HelmClient.upgrade_in…
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.