Reference library

Python Code Samples

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

85 matches
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=…
12 0 Open
Automation & scripting easy

How to Build an argparse CLI That Filters File Lines by Keyword in Python

This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.

argparse cli filter
Python
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
    parser.add_argument("input", type=str, help="File to read")
    parser.add_argument("keyword", type=str, help="Keyword to filter lines")
    parser.add_argument("--contains", action="sto…
13 0 Open
Automation & scripting easy

How to Build an argparse Command-Line Tool in Python

Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.

argparse cli command-line
Python
import argparse
import os
from pathlib import Path


def process_file(filepath, verbose=False):
    """Read a file and report its size and line count."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")

    content = path.read_text()
    lines = conten…
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",
   …
14 0 Open
Automation & scripting easy

How to Decrypt a GPG File with a Passphrase in Python

Decrypt a GPG-encrypted file using a passphrase via the gpg CLI wrapped in a reusable Python function.

gpg encryption subprocess
Python
import subprocess
import tempfile
from pathlib import Path


def decrypt_gpg_file(input_file: str, passphrase: str) -> str:
    """Decrypt a GPG file using a passphrase and return the plaintext."""
    result = subprocess.run(
        ["gpg", "--batch", "--yes", "--passphrase", passphrase, "--decrypt", input_file],
  …
13 0 Open
Automation & scripting medium

How to Generate Project Statistics Including Lines of Code and Complexity in Python

Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.

code metrics lines of code cyclomatic complexity
Python
import os
from pathlib import Path

def count_lines_of_code(filepath):
    """Counts lines of code in a Python file, excluding blank lines and comments."""
    try:
        with open(filepath, 'r') as f:
            lines = f.readlines()
        code_lines = [line for line in lines if line.strip() and not line.strip()…
38 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_…
14 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=…
13 0 Open
Automation & scripting easy

How to Parse Terraform Plan Output in Python

Parse mock Terraform plan output text into structured add, change, and destroy lists using Python.

terraform parsing automation
Python
import json
from typing import Dict, List

def parse_terraform_plan_output(plan_output_text: str) -> Dict[str, List[str]]:
    """
    Parses a mock Terraform plan output text into a structured dictionary.
    """
    parsed: Dict[str, List[str]] = {"add": [], "change": [], "destroy": []}

    for line in plan_output_…
10 0 Open
Automation & scripting easy

How to Sort Command-Line Arguments in Python

Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.

argparse cli sorting
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
    parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
    parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
    args =…
12 0 Open
Automation & scripting medium

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.

kubernetes yaml automation
Python
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()

  …
12 0 Open
Automation & scripting easy

How to stage and commit all changes with Git in Python

Run git add -A and git commit from Python using subprocess to automate staging and committing all file changes in one step.

git subprocess automation
Python
import subprocess
from pathlib import Path

def stage_and_commit_all(commit_message: str) -> None:
    """Stage all changes and create a commit with the given message."""
    repo_root = Path.cwd()
    if not (repo_root / ".git").exists():
        raise RuntimeError("Not inside a Git repository")

    subprocess.run([…
11 0 Open
Automation & scripting easy

How to validate argparse CLI commands in Python

Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.

argparse cli validation
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
    parser.add_argument("name", type=str, help="Your name.")
    parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
    parser.add_argument("--verbose", action="store_t…
12 0 Open
Automation & scripting easy

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.

certbot letsencrypt automation
Python
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…
15 0 Open
Automation & scripting easy

Parse nginx access log top IPs in Python

Reads an nginx access log line by line, extracts the client IP, and returns the most frequent IPs using a regex and Counter.

nginx log parsing regex
Python
import re
from collections import Counter

def top_ips(log_file, n=10):
    ip_pattern = re.compile(r'^(\S+)')
    ip_counts = Counter()

    with open(log_file, 'r') as f:
        for line in f:
            match = ip_pattern.match(line)
            if match:
                ip_counts[match.group(1)] += 1

    return…
13 0 Open
Git + Python easy

Create a Mock GitHub Release API in Python for Testing gh CLI

Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.

mock-api github testing
Python
import json
from unittest.mock import patch, Mock

class GitHubReleaseAPI:
    """Mock GitHub Releases API for testing gh CLI stub behavior."""
    
    def __init__(self):
        self.releases = {}
        self.counter = 1
    
    def create_release(self, repo, tag, name=None, notes=None):
        release_id = self…
16 0 Open
Git + Python easy

Get Git Status Info in Python

Run git commands from Python to gather branch name, number of changes, total commits, and clean status, returning them as a dict.

git subprocess automation
Python
import subprocess
import json
from pathlib import Path


def get_git_status(repo_path="."):
    """Return basic git info about a repository as a dict."""
    try:
        branch = subprocess.check_output(
            ["git", "branch", "--show-current"],
            cwd=repo_path,
            stderr=subprocess.DEVNULL,…
11 0 Open
Git + Python easy

How to Build a Git Helper Class in Python

A beginner-friendly GitHelper class that wraps common git commands (status, log, branch) into reusable Python methods with structured output.

git subprocess automation
Python
import subprocess
import json
from pathlib import Path


class GitHelper:
    def __init__(self, repo_path="."):
        self.repo = Path(repo_path)

    def run(self, *args):
        result = subprocess.run(
            ["git", *args],
            cwd=self.repo,
            capture_output=True,
            text=True,…
12 0 Open
Git + Python easy

How to Get Git Status and Log in Python

A beginner-friendly helper that runs git status and git log from Python using subprocess, with safe handling for non-repo directories.

git subprocess cli
Python
import subprocess
from pathlib import Path


def git_status(path: str = ".") -> str:
    """Return the current git status as a string."""
    result = subprocess.run(
        ["git", "status", "--short"],
        cwd=path,
        capture_output=True,
        text=True
    )
    return result.stdout.strip() or "No cha…
13 0 Open
Git + Python easy

How to List Changed Files in the Last Git Commit with Python

Runs `git diff --name-only HEAD~1 HEAD` via subprocess to list the names of files changed in the most recent commit.

git subprocess automation
Python
import subprocess

def list_changed_files():
    result = subprocess.run(
        ["git", "diff", "--name-only", "HEAD~1", "HEAD"],
        capture_output=True,
        text=True,
        check=True
    )
    files = result.stdout.strip().splitlines()
    return files

if __name__ == "__main__":
    changed = list_cha…
13 0 Open
Git + Python easy

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.

git subprocess automation
Python
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…
13 0 Open
Git + Python easy

Upload Assets to GitHub Release with Python Mock

Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.

git github releases
Python
import json
import os
import tempfile
from datetime import datetime

class ReleaseUploader:
    """Simulates uploading assets to a release with a mock server."""
    
    def __init__(self, owner: str, repo: str, tag: str):
        self.owner = owner
        self.repo = repo
        self.tag = tag
        self.uploade…
11 0 Open
Cloud + Python medium

Build a URL Shortener Client with Python

A Python class that shortens long URLs and resolves short codes using a REST API built with requests.

url shortener api
Python
import json
import sys
import requests

class URLShortenerClient:
    def __init__(self, base_url="http://tinyurl.com"):
        self.base_url = base_url

    def shorten_url(self, long_url):
        payload = {"url": long_url}
        headers = {"Content-Type": "application/json"}
        response = requests.post(f"{…
54 0 Open
Cloud + Python medium

Exponential Backoff with Jitter for Cloud API Calls in Python

A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.

retry backoff jitter
Python
import random
import time


def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
    for attempt in range(1, retries + 1):
        delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
        jitter = delay * random.uniform(-jitter_factor, jitter_factor)
        effect…
18 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.