Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Add Type Hints to Function Parameters and Return in Python
Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.
from typing import List, Optional, Dict
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
def full_name(first: str, last: Optional[str] = "") -> str:
return f"{first} {last}".strip()
def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
us…
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…
Cache expensive function with lru_cache in Python
Use functools.lru_cache to memoize an expensive recursive function and show the dramatic speedup on repeated calls.
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def expensive_operation(n):
"""Simulate an expensive Fibonacci-like calculation."""
if n < 2:
return n
return expensive_operation(n - 1) + expensive_operation(n - 2)
if __name__ == "__main__":
# First call (uncached) - take…
Call a Function Dynamically by Name in Python
Use globals() to look up and call a function by its name as a string, with optional arguments.
def greet():
return "Hello from greet!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
func_name = "add"
args = (3, 5)
# Call function dynamically by name from globals
result = globals()[func_name](*args)
print(f"{func_name}({', '.join(ma…
Create a retry decorator with max attempts in Python
A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.
import functools
import time
def retry(max_attempts, delay=0.1):
"""Retry a function up to max_attempts times on exception."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
…
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 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 Compare Two Implementations with timeit in Python
Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.
import timeit
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
if __name__ == "__main__":
n = 10
iterations = 10000
iterative_time = timeit…
How to Compose Two Functions into a Single Callable in Python
Combine two Python functions into a single callable using a compose helper, then apply the chained call.
def add_one(x):
return x + 1
def double(x):
return x * 2
def compose(f, g):
return lambda x: f(g(x))
add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)
result1 = add_then_double(5)
result2 = double_then_add(5)
print(f"add_one then double(5) = {result1}")
print(f"doub…
How to Convert a List to an Iterator in Python with iter()
This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.
def main():
# Original list
fruits = ["apple", "banana", "cherry"]
# Convert the list to an iterator using iter()
fruit_iterator = iter(fruits)
# Retrieve items one at a time with next()
print(next(fruit_iterator)) # apple
print(next(fruit_iterator)) # banana
print(next(fruit_iterat…
How to Count Items with Default Parameters in Python
Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.
def count_items(items, start=0, step=1):
"""Count items in a list with configurable start value and step."""
count = start
for item in items:
print(f"{count}: {item}")
count += step
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
print("Default parameters (start=0…
How to Create Functions with Default Parameters in Python
This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Generate a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def create_profile(username="anonymous", age=0, city="Unknown", active=True):
"""Create a user profile dictionary with default values."""
r…
How to Create Generator Functions with yield in Python
Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.
def fibonacci_sequence(limit):
"""Generate Fibonacci numbers up to a given limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
fib_gen = fibonacci_sequence(100)
for number in fib_gen:
print(number, end=" ")
print()
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 Create a Higher-Order Function in Python (Apply Twice)
This code defines a higher-order function that takes another function and a value, then applies the function twice to the value and returns the result.
def apply_twice(func, value):
return func(func(value))
def add_ten(x):
return x + 10
def square(x):
return x ** 2
if __name__ == "__main__":
print(apply_twice(add_ten, 5))
print(apply_twice(square, 3))
How to Create a Timing Decorator in Python
A Python decorator that measures and prints the execution time of any function using time.perf_counter.
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
elapsed = end - start
print(f"{func.__name__} took {elapsed:.6f} seconds"…
How to Define a Function with Default Parameter Values in Python
This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.
def greet(name: str = "World", punctuation: str = "!") -> str:
"""Return a greeting message using default parameter values."""
message = f"Hello, {name}{punctuation}"
return message
if __name__ == "__main__":
# Call with no arguments – uses both defaults
print(greet())
# Call with one argume…
How to Document Python Functions with Google Style Docstrings
Document a Python function with a Google style docstring to describe arguments and return values clearly.
def calculate_rectangle_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle in meters.
width (float): The width of the rectangle in meters.
Returns:
float: The area of the rectangle in square meters.
…
How to Group a List into Chunks in Python
Split a list into smaller groups of a fixed size using a reusable function with a default parameter.
def make_groups(numbers, group_size=2):
"""Splits a list into smaller groups of a given size."""
groups = []
for i in range(0, len(numbers), group_size):
groups.append(numbers[i:i + group_size])
return groups
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7]
print("Default size…
How to Implement Memoized Fibonacci in Python with functools.cache
Use functools.cache to memoize a recursive Fibonacci function, avoiding repeated computation and dramatically speeding up the calculation.
from functools import cache
@cache
def fibonacci(n: int) -> int:
"""Return the n-th Fibonacci number (0-indexed)."""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fibonacci({i}) = {fibonacci(i)}")
print(f"Cache…
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
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.