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 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 _…
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.