Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Safely Convert a List of Strings to Integers in Python
Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.
def safe_to_int(values):
"""Safely convert a list of strings to integers, skipping invalid entries."""
result = []
errors = []
for value in values:
try:
result.append(int(value))
except (ValueError, TypeError):
errors.append(value)
return result, errors
if …
How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def…
Catch ValueError and print friendly message in Python
Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.
try:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
Handle ValueError and ZeroDivisionError in Python with try except
Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.
def safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ValueError as e:
print(f"ValueError caught: {e}")
return None
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
return result
# Test cases
print(safe_divide…
How to Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, r…
How to Validate Input and Raise TypeError in Python
Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.
def validate_number(value):
if not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__}")
return value * 2
if __name__ == "__main__":
try:
print(validate_number(5))
print(validate_number("hello"))
except TypeError as e:
print(…
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…
How to Convert Images Between Formats in Python
Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.
from PIL import Image
import sys
def convert_image_format(input_path, output_path):
try:
img = Image.open(input_path)
img.save(output_path)
print(f"Converted {input_path} to {output_path}")
except FileNotFoundError:
print(f"Error: File {input_path} not found")
sys.exit(…
Validate dictionary data with sets in Python
Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.
def validate_data(data, required_keys, allowed_values=None):
"""
Validate a dictionary against required keys and optional allowed value sets.
Returns a list of validation errors (empty list if valid).
"""
errors = []
# Check for missing required keys
missing = set(required_keys) - set(…
Python Factory Method: Create Shapes by Type String
A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.
class Shape:
def draw(self):
raise NotImplementedError
class Circle(Shape):
def draw(self):
return "Drawing a circle"
class Square(Shape):
def draw(self):
return "Drawing a square"
class Triangle(Shape):
def draw(self):
return "Drawing a triangle"
class ShapeFact…
Build a Complete Web Scraper with Requests and BeautifulSoup in Python
Scrape multiple paginated pages from a website using Requests and BeautifulSoup, with retry logic, error handling, and CSV export.
import requests
from bs4 import BeautifulSoup
import csv
import time
from typing import List, Dict, Optional
class WebScraper:
def __init__(self, base_url: str, output_file: str = "scraped_data.csv"):
self.base_url = base_url
self.output_file = output_file
self.session = requests.Session()…
How to Clean Old Temp Files in Python
A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.
import os
import time
from pathlib import Path
def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
"""
Remove files in directory older than the specified age.
Args:
directory: Path to directory to clean
max_age_seconds: Maximum age in seconds (default: 1 week)
…
How to apply Kubernetes YAML files from a folder in Python
Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.
import os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml
def apply_yaml_folder(folder_path):
"""Apply all YAML files in a folder using the Kubernetes mock client."""
# Load mock configuration
config.load_kube_config()
k8s_client = client.ApiClient()
…
How to Create a Git Branch if it Doesn't Exist in Python
Utility script that checks if a Git branch exists locally and either creates it or checks it out, with error handling.
import subprocess
import sys
def ensure_branch(branch_name):
"""Create a Git branch if it doesn't exist, otherwise checkout it."""
try:
# Check if the branch exists locally
result = subprocess.run(
["git", "branch", "--list", branch_name],
capture_output=True,
…
How to Mirror a Bare Git Repository Backup in Python
Run a git clone --bare subprocess to create a timestamped bare-repo backup folder with error handling.
import subprocess
import shlex
from pathlib import Path
from datetime import datetime
def mirror_bare_repo(source_url: str, backup_dir: str) -> str:
"""Mirror a bare git repository to a timestamped backup folder."""
backup_path = Path(backup_dir)
backup_path.mkdir(parents=True, exist_ok=True)
timest…
How to Push Git Tags to a Remote with Python
Push specified git tags (or all tags) to a remote repository using Python's subprocess module with error handling.
import subprocess
import sys
def push_tags_to_remote(remote: str = "origin", tags: list[str] | None = None) -> None:
"""
Push git tags to a remote repository.
If no tags are given, push all local tags.
"""
if tags:
subprocess.run(["git", "push", remote, *tags], check=True)
else:
…
How to Run Git Commands from Python with subprocess
This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.
import subprocess
def git_status():
"""Return a short, human-readable git status."""
try:
output = subprocess.run(
["git", "status", "--short"],
capture_output=True,
text=True,
check=True,
).stdout.strip()
return output if output else "W…
How to Parse Cloud JSON Data in Python
A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.
import json
from typing import Dict, Any
def parse_cloud_data(payload: str) -> Dict[str, Any]:
"""Parse a JSON payload from a cloud service into a clean dict."""
try:
data = json.loads(payload)
return {
"status": data.get("status", "unknown"),
"region": data.get("region…
How to Mock BugSnag Notify in Python
Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.
import mock
bugsnag = mock.MagicMock()
def notify_error(message, severity="error"):
bugsnag.notify(message, severity=severity)
if __name__ == "__main__":
notify_error("Test error", severity="warning")
bugsnag.notify.assert_called_once_with("Test error", severity="warning")
print("Mocked BugSnag noti…
How to Serialize Cache Values with JSON and Pickle in Python
Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.
import json
import pickle
from unittest.mock import Mock
def serialize(value, method="json"):
"""Serialize a cache value using JSON or pickle with type checking."""
if method == "json":
try:
return json.dumps(value).encode("utf-8")
except TypeError as e:
raise ValueErro…
Chaos Inject Random Failures in Python
Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.
import random
def unreliable_function(success_rate: float = 0.7) -> str:
"""Simulate a function that sometimes fails."""
if random.random() > success_rate:
raise ConnectionError("Simulated network failure")
return "Operation completed successfully"
if __name__ == "__main__":
random.seed(42)…
How to Mock Fault Injection Percentage in Python
Simulate a service with a 30% failure rate using random.random to test error handling and retries.
import random
class Service:
def call(self):
if random.random() < 0.3: # 30% failure rate
raise ConnectionError("Simulated network fault")
return "ok"
def main():
svc = Service()
random.seed(42) # deterministic for demonstration
results = []
for _ in range(10):
…
How to Mock a Try Confirm Cancel Pattern in Python
Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.
class TCC:
def __init__(self):
self.confirmed = False
self.cancelled = False
def confirm(self):
self.confirmed = True
return "confirmed"
def cancel(self):
self.cancelled = True
return "cancelled"
def try_confirm(self):
try:
result =…
How to Ship Logs to an Aggregator Endpoint in Python
Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.
import json
import requests
from datetime import datetime, timezone
LOG_ENTRIES = [
{"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
{"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
{"timestamp": "2024-01-15T10:00:10Z", "level": "E…
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.