Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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:
…
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.
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…
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.
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…
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.
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…
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.
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…
Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
import secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":…
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.
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")
…
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.
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="…
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.
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.…
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.
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…
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.
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=…
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.
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…
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.
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…
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.
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",
…
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.
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_…
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.
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=…
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.
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 =…
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.
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…
How to Create Interactive CLI Prompts in Python with questionary
Build mock interactive command-line prompts using questionary's select and text widgets with graceful handling of user cancellation.
import questionary
def main():
# Mock interactive prompts using questionary's select and text
choice = questionary.select(
"What is your favorite programming language?",
choices=["Python", "JavaScript", "Go", "Rust"]
).ask()
# ask() returns None if user cancels; handle gracefully
…
How to Mock CLI Output in Typer with unittest.mock
Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.
import typer
from unittest.mock import patch
import io
app = typer.Typer()
@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
"""Greet a person with optional formatting."""
message = f"Hello {name}, age {age}"
if uppercase:
message = message.upper()
typer.echo(messag…
How to Use prompt_toolkit Autocomplete in Python
Demonstrates an interactive command-line prompt with autocomplete using prompt_toolkit's WordCompleter and a mock dataset.
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
def main():
"""Demo of prompt_toolkit autocomplete with a mock dataset."""
# A simple mock "database" of programming languages
languages = [
"Python", "Java", "JavaScript", "TypeScript", "C++", "C#",
"Go"…
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.