Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

27 matches
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
Automation & scripting easy

Batch Rename Hundreds of Files in Python

Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.

automation files pathlib
Python
import os
from pathlib import Path

def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
    """Rename all files with given extension in directory to prefix_{counter}.ext."""
    path = Path(directory)
    if not path.is_dir():
        print(f"Directory '{directory}' does not exist.")
…
55 0 Open
Automation & scripting easy

Convert Markdown to HTML in Python (Batch)

Convert every Markdown file in a directory to HTML with the Python markdown library, saving each result with an .html extension.

markdown html batch
Python
import markdown
from pathlib import Path


def convert_md_to_html(source_dir: str, dest_dir: str) -> list[str]:
    src = Path(source_dir)
    dst = Path(dest_dir)
    dst.mkdir(parents=True, exist_ok=True)

    converted_files = []
    for md_file in src.glob("*.md"):
        html_content = markdown.markdown(md_file.…
14 0 Open
Automation & scripting easy

Fetch weather API mock and write dashboard HTML in Python

This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.

weather-api dashboard html
Python
from datetime import datetime
import json
import os


def fetch_weather_mock(city: str) -> dict:
    """Return a mock weather payload for a given city."""
    return {
        "city": city,
        "temperature_c": 21.5,
        "condition": "Partly Cloudy",
        "humidity": 58,
        "wind_kph": 12.3,
        "u…
14 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 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
Automation & scripting easy

How to Build a Simple argparse CLI in Python

Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.

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

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
    parser.add_argument("name", help=…
13 0 Open
Automation & scripting easy

How to Create a Simple Python CLI with argparse

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.

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

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI tool that greets users."
    )
    parser.add_argument(
        "name",
   …
15 0 Open
Automation & scripting easy

How to Download a List of URLs to a Directory in Python

This script downloads a list of URLs into a specified directory, creating the folder if needed and keeping original filenames.

urllib download file-io
Python
import urllib.request
from pathlib import Path

def download_urls(url_list, directory):
    """Download each URL in url_list into directory, keeping original filenames."""
    save_dir = Path(directory)
    save_dir.mkdir(parents=True, exist_ok=True)
    
    for url in url_list:
        filename = url.rstrip('/').spl…
14 0 Open
Automation & scripting easy

How to Implement argparse CLI Command in Python

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments, flags, and prints a customizable greeting.

argparse cli command-line
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="A simple CLI tool to greet users.")
    parser.add_argument("name", help="Your name")
    parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
    parser.add_argument("--uppercase", action="store_…
15 0 Open
Automation & scripting easy

How to Parse CLI Arguments in Python with argparse

Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.

argparse cli command-line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
    parser.add_argument("--name", default="world", help="Name to greet")
    parser.add_argument("--greeting", default="Hello", help="Greeting word")
    parser.add_argument("--uppercase", action=…
14 0 Open
Automation & scripting easy

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.

traceroute simulation network
Python
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…
15 0 Open
Automation & scripting easy

How to Split PDF Pages into Ranges in Python

Simulates splitting a PDF into page ranges by validating and returning structured range splits for automation workflows.

pdf automation file-processing
Python
import os

def split_pdf_ranges(pdf_name, num_pages, ranges):
    """
    Simulates splitting a PDF by returning the page ranges that would be split.

    Args:
        pdf_name (str): Name of the PDF file.
        num_pages (int): Total number of pages in the PDF.
        ranges (list of tuple): List of (start, end) …
12 0 Open
Automation & scripting easy

How to Write an IP Block List to hosts.deny in Python

This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.

hosts.deny ip-block ipaddress
Python
from ipaddress import ip_network

def write_hosts_deny(ip_list, output_file="hosts.deny"):
    with open(output_file, "w") as f:
        for ip in ip_list:
            try:
                ip_network(ip)
                f.write(f"ALL: {ip}\n")
            except ValueError:
                continue
    print(f"Written…
14 0 Open
Automation & scripting easy

Monitor Disk Usage and Alert in Python

A Python script that checks disk usage percentage against a threshold and returns an ALERT or OK message with free space details.

disk monitoring shutil
Python
import shutil
import os

def check_disk_usage(path="/", threshold=85.0):
    usage = shutil.disk_usage(path)
    percent_used = (usage.used / usage.total) * 100
    
    if percent_used > threshold:
        return (f"ALERT: Disk usage at {percent_used:.1f}% on {path} "
                f"(exceeds {threshold}% threshold…
12 0 Open
Automation & scripting easy

Rename Files in Folder with Numeric Prefix in Python

Renames all files in a folder by adding a sequential numeric prefix (e.g., 01_, 02_) to each filename using pathlib.

file-renaming pathlib automation
Python
from pathlib import Path

def rename_with_numeric_prefix(folder_path):
    folder = Path(folder_path)
    for index, file_path in enumerate(folder.iterdir(), start=1):
        if file_path.is_file():
            new_name = f"{index:02d}_{file_path.name}"
            new_path = file_path.with_name(new_name)
           …
13 0 Open
Automation & scripting easy

Stress CPU Threads with a Mock Compute in Python

Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.

threading cpu-stress parallelism
Python
import threading
import time


def stress_cpu(iterations: int):
    result = 0
    for i in range(iterations):
        result += i * i % 1000
    return result


def run_mock_stress(thread_count: int, iterations: int):
    threads = []
    for tid in range(thread_count):
        t = threading.Thread(target=lambda: str…
12 0 Open
Automation & scripting easy

Toggle VPN Mock Network Manager Script in Python

Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.

vpn simulation automation
Python
import time

class MockVPNManager:
    def __init__(self):
        self.is_connected = False
        self.servers = ["us-west", "eu-central", "asia-east"]
        self.active_server = None

    def toggle(self):
        if self.is_connected:
            self.disconnect()
        else:
            self.connect()

    d…
11 0 Open
Git + Python easy

Bisect Good Bad Automation Script in Python

This Python script implements a binary search to find the first bad version in a list, simulating an automation script for git bisect.

bisect binary-search git
Python
import bisect

def find_first_bad(versions):
    """Given a list of version objects with .is_bad(), find first bad version."""
    lo, hi = 0, len(versions)
    while lo < hi:
        mid = (lo + hi) // 2
        if versions[mid].is_bad():
            hi = mid
        else:
            lo = mid + 1
    return lo

clas…
17 0 Open
Git + Python easy

How to Auto-Suggest a SemVer Bump From Git Commit Messages in Python

This code scans Git commit messages (recent or sample) and suggests the next Semantic Versioning bump type — major, minor, patch, or none.

semver git automation
Python
import re
import subprocess
from pathlib import Path


def get_commit_messages(path="."):
    """Read commit messages from a repo or use sample messages."""
    if (Path(path) / ".git").exists():
        out = subprocess.run(
            ["git", "-C", path, "log", "--pretty=%s"], capture_output=True, text=True
       …
13 0 Open
Git + Python easy

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.

git subprocess branch
Python
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,
         …
10 0 Open
Git + Python easy

How to Create a Git Commit with Message Template in Python

Run a git commit from Python using a standardized message template built from a commit type and description.

git subprocess automation
Python
import subprocess
import sys


def commit_with_template(commit_type: str, description: str) -> None:
    message = f"{commit_type}: {description}"
    try:
        subprocess.run(["git", "commit", "-m", message], check=True)
        print(f"Committed: {message}")
    except subprocess.CalledProcessError as e:
        …
12 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.