Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
Build a Context Manager in Python with contextlib.contextmanager
Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode='r'):
"""Context manager that opens and closes a file safely."""
file = open(filename, mode)
yield file
file.close()
if __name__ == "__main__":
# Write a sample file
with managed_file("sample.txt", "w") as f…
Build a Progress Callback Function for Loops in Python
Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.
def run_with_progress(items, desc="Processing", step_callback=None):
"""Run a loop with progress updates via callback."""
total = len(items)
for idx, item in enumerate(items):
# Process the item (simulated work here)
result = item * 2
# Build progress data dictionary
if ste…
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 Partial Functions with functools.partial in Python
Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.
```python
from functools import partial
def power(base, exponent):
"""Calculate base raised to the exponent power."""
return base ** exponent
# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
if __name__ == "__main__":
squares = [square(x)…
How to Build a Simple Decorator That Logs Function Calls in Python
This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.
import functools
import time
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} return…
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 Create a Counter Closure in Python
Build a closure in Python that remembers and increments a counter across calls without using global variables.
def create_counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
if __name__ == "__main__":
counter = create_counter(10)
print(counter())
print(counter())
print(counter())
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 Use Default Parameters in Python Functions
Create a simple function with default parameters to build flexible, reusable greetings in Python.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a personalized greeting message."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", greeting="Hey", punctuation="?"))…
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.