Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Capitalize First Letter of Each Word in Python
Capitalizes the first letter of every word in a string using the built-in title() method.
def capitalize_words(text):
return text.title()
if __name__ == "__main__":
sample = "hello world from python"
result = capitalize_words(sample)
print(result)
How to Convert snake_case to Title Case in Python
Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.
def to_title_case(snake_str):
words = snake_str.split("_")
return " ".join(word.capitalize() for word in words)
if __name__ == "__main__":
examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
for example in examples:
print(f"{example!r:35} -> {to_tit…
How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
import html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("…
How to Format Text in Python
A beginner-friendly helper that cleans and changes the case of a string, with options for title, upper, lower, and capitalize.
def format_text(text, case="title", strip_whitespace=True, remove_extra_spaces=True):
"""
Formats a string based on common beginner needs.
Args:
text: Input string to format
case: "title", "upper", "lower", or "capitalize"
strip_whitespace: Remove leading/trailing whitespace
…
How to Build an Error Code Enum in Python
Define an API error code enum with descriptions and build structured error payloads for HTTP responses.
from enum import Enum
class APIErrorCode(Enum):
SUCCESS = 0
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
CONFLICT = 409
INTERNAL_ERROR = 500
def describe_error(code):
descriptions = {
APIErrorCode.SUCCESS: "Request completed successfully",
APIE…
How to Emit Deprecation Warnings in Python
Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.
import warnings
class OldAPI:
def __init__(self):
warnings.warn(
"OldAPI is deprecated; use NewAPI instead.",
DeprecationWarning,
stacklevel=2,
)
self.data = []
def add(self, item):
warnings.warn(
"OldAPI.add() is deprecated; us…
Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
EXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_S…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
How to Fetch Weather Data from a Public API in Python
Fetches and parses weather data from a free public API using only the Python standard library.
import urllib.request
import json
def get_weather(city):
base_url = f"https://wttr.in/{city}?format=j1"
with urllib.request.urlopen(base_url) as response:
data = json.loads(response.read().decode())
current = data["current_condition"][0]
temp = current["temp_C"]
desc = current["weatherDesc…
How to Find HTML Elements by Tag, Class, ID, CSS Selector, and Attribute in BeautifulSoup
Parse an HTML string with BeautifulSoup and demonstrate five distinct ways to locate elements: by tag name, by class, by ID, by CSS selector, and by attribute.
from bs4 import BeautifulSoup
html_content = """
<html><body>
<h1 id="title" class="heading">Hello World</h1>
<p class="content">First paragraph</p>
<p class="content special">Second paragraph</p>
<a href="https://example.com" class="link">Click here</a>
<div id="footer">
<p>© 2024</p>
…
How to Scrape Headlines from a News Website Using Beautiful Soup in Python
Scrape headline text from a news website using requests and Beautiful Soup with a CSS selector.
import requests
from bs4 import BeautifulSoup
def scrape_headlines(url: str, selector: str) -> list:
"""
Scrape headlines from a news website using Beautiful Soup.
Args:
url: The URL of the news website.
selector: CSS selector for headline elements.
Returns:
List of h…
Scrape HTML Tables and Convert Them to CSV Using Beautiful Soup in Python
Scrape a Wikipedia table with Beautiful Soup and write the data to a CSV file using the csv module.
import requests
from bs4 import BeautifulSoup
import csv
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tables = soup.find_all('table', {'class': 'wikitable'})
if tables:
target_table = tables[2]
rows =…
How to Build a Two-Way Dictionary in Python
Implement a BiDict class that supports both forward key-to-value and reverse value-to-key lookups with a simple add, delete, and update API.
class BiDict:
def __init__(self, data=None):
self.forward = {}
self.backward = {}
if data:
self.update(data)
def update(self, data):
for key, value in data.items():
self[key] = value
def __setitem__(self, key, value):
self.forward[key] = val…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
How to Heapify a List into a Min Heap with heapq in Python
Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.
import heapq
data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)
heapq.heapify(data)
print("Min heap:", data)
popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
Circuit Breaker Pattern in Python for LLM API Calls
Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.
import time
class CircuitBreaker:
def __init__(self, failure_threshold=3, recovery_timeout=5):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.state = "closed"
self.last_failure_time = None
def call(self, …
How to Build a System-User-Assistant Message List in Python
Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Message:
role: str
content: str
@dataclass
class Conversation:
messages: List[Message] = field(default_factory=list)
def add_system(self, content: str) -> None:
self.messages.append(Message(role="system", con…
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 Parse an LLM Response in Python
This code parses a JSON string from an LLM response, stripping code fences and handling common issues like whitespace, returning a Python dictionary.
import json
from typing import Any, Dict, List
def parse_llm_response(response: str) -> Dict[str, Any]:
"""Parse a JSON string from an LLM response, handling common edge cases."""
# Remove code fences if present
cleaned = response.strip()
if cleaned.startswith("
How to Retry LLM Calls on Rate Limit Errors in Python
Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.
import time
import random
def mock_llm_call():
"""Simulates an LLM API call that may raise a rate limit error."""
if random.random() < 0.4: # 40% chance of rate limit
raise RateLimitError("Rate limit exceeded. Try again later.")
return {"response": "Hello world from mock LLM"}
class RateLimitE…
How to build a function calling schema dict in Python
Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.
import json
from typing import Dict, Any, List, Optional
def build_function_schema(
name: str,
description: str,
parameters: Optional[Dict[str, Any]] = None,
required: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Build an OpenAI-compatible function calling schema dictionary."""
schema: …
How to implement exponential backoff for LLM API calls in Python
A decorator that retries flaky LLM API calls with exponential delay, using a mock client to demonstrate the pattern.
import time
import random
class MockLLM:
def call(self, prompt):
if random.random() < 0.7: # 70% chance of transient failure
raise ConnectionError("API unavailable")
return f"LLM response for: {prompt}"
def with_exponential_backoff(max_retries=5, base_delay=0.1):
def decorator(fu…
Track GitHub Repository Growth in Python
A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.
import requests
import json
from datetime import datetime, timedelta
def track_repo_growth(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
headers = {"Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
data = response.json()
name = data…
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
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.