Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
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 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.
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',
…
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.
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 _…
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.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
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…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.