Reference library

Functions & basics

Reusable building blocks — parameters, returns, scope, and clear function design.

49 matches
Functions & basics easy

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.

type-hints typing annotations
Python
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…
16 0 Open
Functions & basics easy

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.

timeit benchmark performance
Python
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…
14 0 Open
Functions & basics easy

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.

context manager contextlib file handling
Python
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…
15 0 Open
Functions & basics easy

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.

callback loops progress
Python
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…
14 0 Open
Functions & basics easy

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.

lru_cache caching decorators
Python
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…
16 0 Open
Functions & basics easy

Calculate Time Difference Across Time Zones in Python

Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.

datetime timezone timedelta
Python
from datetime import datetime, timezone, timedelta

def time_difference(from_tz_offset, to_tz_offset):
    """
    Calculate time difference in hours between two time zones given their offsets from UTC.
    Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
    """
    tz1 = timezone(timedelta(hours=from_tz_offset…
46 0 Open
Functions & basics easy

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.

globals dynamic-dispatch reflection
Python
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…
13 0 Open
Functions & basics easy

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.

decorator retry error-handling
Python
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:
                …
12 0 Open
Functions & basics easy

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.

cli textwrap formatting
Python
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:
        …
12 0 Open
Functions & basics easy

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.

argparse cli dry-run
Python
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…
11 0 Open
Functions & basics easy

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.

functools partial higher-order-functions
Python
```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)…
12 0 Open
Functions & basics easy

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.

decorator logging functools
Python
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…
11 0 Open
Functions & basics easy

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.

timeit benchmark performance
Python
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…
13 0 Open
Functions & basics easy

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.

iter iterator built-in
Python
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…
12 0 Open
Functions & basics easy

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.

functions default-parameters loops
Python
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…
11 0 Open
Functions & basics easy

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.

default-parameters functions arguments
Python
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…
14 0 Open
Functions & basics easy

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.

generator yield fibonacci
Python
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()
11 0 Open
Functions & basics easy

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.

higher-order functions composition
Python
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))
12 0 Open
Functions & basics easy

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.

decorator timing perf_counter
Python
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"…
12 0 Open
Functions & basics easy

How to Create an Iterator Class with Dunder Methods in Python

A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.

iterators dunder-methods class
Python
class Counter:
    def __init__(self, start=0, end=5):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        value = self.current
        self.current += 1
        return val…
13 0 Open
Functions & basics easy

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.

docstrings documentation functions
Python
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.
 …
13 0 Open
Functions & basics easy

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.

list slicing functions
Python
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…
15 0 Open
Functions & basics easy

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.

fibonacci memoization functools
Python
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…
15 0 Open
Functions & basics easy

How to Parse Function Parameters with Defaults in Python

Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Greet a person with customizable greeting and punctuation."""
    return f"{greeting}, {name}{punctuation}"

def describe_fruit(fruit, color="unknown", ripe=False):
    """Describe a fruit with optional attributes."""
    status = "ripe" if ripe else "not ripe…
14 0 Open

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.