Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

85 matches
Functions & basics easy

Format CLI help text in Python

Build a readable usage string for a command-line tool, aligning flags and wrapping descriptions with the textwrap module.

cli textwrap formatting
Python
import textwrap


def format_help(command_name: str, description: str, options: list[tuple[str, str]]) -> str:
    """Format CLI help text into a readable usage string."""
    header = f"Usage: {command_name} [OPTIONS]"
    lines = [header, "", description, "", "Options:"]

    for flag, help_text in options:
        …
12 0 Open
Functions & basics easy

How to Add a Dry Run Flag to a Python CLI Command

Build a Python CLI command with a --dry-run flag that previews actions and exits before making real changes.

argparse cli dry-run
Python
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Sample CLI command with dry-run flag")
    parser.add_argument("--name", required=True, help="Name to greet")
    parser.add_argument("--dry-run", action="store_true", dest="dry_run",
                        help="Show what would…
11 0 Open
Functions & basics medium

How to Build a Subcommand Parser Tree with argparse in Python

Create a CLI with nested subcommands (like git) using argparse subparsers, where each subcommand maps to its own handler function.

argparse cli subparsers
Python
import argparse


def cmd_add(args):
    print(f"Adding {args.num1} + {args.num2} = {args.num1 + args.num2}")


def cmd_sub(args):
    print(f"Subtracting {args.num1} - {args.num2} = {args.num1 - args.num2}")


def main():
    parser = argparse.ArgumentParser(prog="calculator")
    subparsers = parser.add_subparsers(d…
12 0 Open
Functions & basics easy

How to Parse Command Line Arguments in Python with argparse

Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.

argparse cli command line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('numbers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
         …
11 0 Open
Functions & basics easy

How to Print Colored Text in Python with ANSI Codes

Define a small Colors class and a colored() helper to print styled terminal text using ANSI escape codes.

ansicodes cli terminal
Python
class Colors:
    RESET = "\033[0m"
    RED = "\033[31m"
    GREEN = "\033[32m"
    YELLOW = "\033[33m"
    BLUE = "\033[34m"
    MAGENTA = "\033[35m"
    CYAN = "\033[36m"
    WHITE = "\033[37m"
    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"


def colored(text, color):
    return f"{color}{text}{Colors.RESET}"


if _…
12 0 Open
Functions & basics easy

How to Read Environment Variables in Python with Default Values

Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.

environment-variables os configuration
Python
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
10 0 Open
Functions & basics easy

How to Validate CLI Integer Option Within a Range in Python

Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.

argparse cli validation
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Validate an integer within a range.")
    parser.add_argument("--value", type=int, required=True, help="Integer to validate")
    parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
    parser.add_argument("--max…
13 0 Open
Errors & debugging easy

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.

testing mocking requests
Python
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…
16 0 Open
Files & data easy

Build a Command-Line To-Do List Application with Data Persistence in Python

A persistent command-line to-do list that saves tasks as JSON, supporting add, show, toggle done, and quit commands.

cli json persistence
Python
import json
import os

TODO_FILE = "todos.json"

def load_todos():
    if not os.path.exists(TODO_FILE):
        return []
    with open(TODO_FILE, "r") as f:
        return json.load(f)

def save_todos(todos):
    with open(TODO_FILE, "w") as f:
        json.dump(todos, f, indent=2)

def show_todos(todos):
    if not…
111 0 Open
Files & data medium

Convert Image to ASCII Art in Python

Convert any image to ASCII art by resizing, converting to grayscale, and mapping pixel brightness to characters using Pillow.

image ascii-art pillow
Python
from PIL import Image
import sys

ASCII_CHARS = "@%#*+=-:. "

def resize_image(image, new_width=100):
    """Resize image maintaining aspect ratio."""
    width, height = image.size
    ratio = height / width
    new_height = int(new_width * ratio * 0.55)  # 0.55 adjusts for font aspect ratio
    return image.resize((…
49 0 Open
Algorithms & data structures easy

Find k Closest Points to Origin in Python

Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.

sorting euclidean-distance geometry
Python
import math

def k_closest(points, k):
    points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
    return points[:k]

if __name__ == "__main__":
    points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
    k = 3
    result = k_closest(points, k)
    print(f"Original points: {points}")
    print(f"K closest points (k…
12 0 Open
Algorithms & data structures easy

How to Compute Cosine Similarity Between Two Vectors in Python

This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.

cosine similarity vectors math
Python
import math

def cosine_similarity(vec_a, vec_b):
    if len(vec_a) != len(vec_b):
        raise ValueError("Vectors must have the same length")
    
    dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
    norm_a = math.sqrt(sum(a * a for a in vec_a))
    norm_b = math.sqrt(sum(b * b for b in vec_b))
    
    i…
13 0 Open
Algorithms & data structures easy

Pair Elements with Next Cyclic Neighbor in Python

Create tuples pairing every element with its next element, wrapping around to the first element for the last one.

pairs cyclic list
Python
def cyclic_pairs(lst):
    if not lst:
        return []
    return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5]
    result = cyclic_pairs(sample)
    print(result)
14 0 Open
Comprehensions & generators easy

Cycle an iterable forever in Python

Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.

generators cycle iteration
Python
def cycle_generator(iterable):
    """Yield items from iterable forever, cycling back to the start."""
    items = list(iterable)  # Convert to list so it can restart
    index = 0
    while True:
        yield items[index]
        index = (index + 1) % len(items)


if __name__ == "__main__":
    colors = ["red", "gre…
13 0 Open
AI & LLM integration patterns medium

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.

circuit-breaker llm resilience
Python
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, …
14 0 Open
AI & LLM integration patterns easy

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.

llm mock testing
Python
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(…
16 0 Open
AI & LLM integration patterns medium

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.

exponential-backoff retries llm
Python
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…
14 0 Open
Automation & scripting easy

Build a Live Countdown Timer for Events in Python

A Python script that displays a real-time countdown to a target date and time, updating every second in the console.

datetime countdown timers
Python
import datetime
import time

def countdown(event_name, target_datetime):
    """Displays a live countdown to a target datetime."""
    while True:
        now = datetime.datetime.now()
        remaining = target_datetime - now
        if remaining.total_seconds() <= 0:
            print(f"\n🚀 {event_name} is happening…
44 0 Open
Automation & scripting medium

Download Images from a Web Page Automatically in Python

Scrape all images from a webpage, filter by extension, and save them to a local folder using requests and BeautifulSoup.

web-scraping requests beautifulsoup
Python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import os

def download_images(url, output_folder="downloaded_images"):
    """Download all images from a given URL."""
    os.makedirs(output_folder, exist_ok=True)
    
    response = requests.get(url)
    response.raise_for_status()
    …
46 0 Open
Automation & scripting easy

How to Build a CLI with argparse in Python

Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.

argparse cli scripting
Python
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI to process files with optional verbose mode."
    )
    parser.add_argument("filenames", nargs="+", help="Files to process")
    parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
 …
11 0 Open
Automation & scripting easy

How to Build a Docker Image Tag Script in Python

Generate consistent Docker image tags from service names and versions with automatic normalization.

docker scripting cli
Python
#!/usr/bin/env python3
"""Mock script for building docker image tags."""


def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
    """Construct a docker image tag."""
    safe_name = service_name.lower().replace("_", "-")
    return f"{registry}/{safe_name}:{version}"


if __name__ == "…
12 0 Open
Automation & scripting easy

How to Build a Python argparse CLI for Beginners

Build a beginner-friendly command-line interface using Python's argparse module with positional and optional arguments.

argparse cli command-line
Python
import argparse

def greet(name, greeting="Hello", uppercase=False):
    message = f"{greeting}, {name}!"
    if uppercase:
        message = message.upper()
    return message

def main():
    parser = argparse.ArgumentParser(description="A simple CLI greet tool for beginners.")
    parser.add_argument("name", help="…
15 0 Open
Automation & scripting easy

How to Build a Simple Python CLI with argparse

Create a friendly command-line greeting tool with argparse that accepts a positional name and optional flags for custom greetings and uppercase output.

argparse cli command-line
Python
import argparse

def greet(name, greeting="Hello", uppercase=False):
    message = f"{greeting}, {name}!"
    return message.upper() if uppercase else message

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="A simple greeting tool to demonstrate argparse basics."
    )
    parser.…
11 0 Open
Automation & scripting easy

How to Build a Simple argparse CLI in Python

Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.

argparse cli automation
Python
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Automate file processing with a simple CLI tool."
    )
    parser.add_argument("filename", help="Path to the input file")
    parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
    parser.add…
13 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.