Reference library

Functions & basics

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

74 matches
Functions & basics easy

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.

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

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.

trampoline tail-recursion decorator
Python
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…
11 0 Open
Functions & basics medium

How to Invalidate Cache When Arguments Change in Python

A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.

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

How to Load a .env File Manually in Python

Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.

dotenv environment-variables file-parsing
Python
import re
from pathlib import Path


def load_dotenv_file(filepath: str) -> dict[str, str]:
    """Parse a .env-style file into a dictionary."""
    env = {}
    path = Path(filepath)

    if not path.exists():
        raise FileNotFoundError(f"Environment file not found: {filepath}")

    for line in path.read_text()…
13 0 Open
Functions & basics easy

How to Merge Lists in Python with Default Parameters

This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.

functions default-parameters list
Python
def merge_lists(list1, list2=["default"]):
    """Merge two lists and return the combined result."""
    return list1 + list2


if __name__ == "__main__":
    # Example with default parameter
    print("With default:", merge_lists([1, 2, 3]))
    
    # Example with both arguments provided
    print("With custom:", me…
13 0 Open
Functions & basics easy

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.

argparse cli command line
Python
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',
         …
11 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…
13 0 Open
Functions & basics medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
13 0 Open
Functions & basics easy

How to Pass a Function as a Callback to map and filter in Python

Shows how to apply custom functions to every element of a list using map and filter callbacks in Python.

map filter callbacks
Python
def double(x):
    return x * 2

def is_even(x):
    return x % 2 == 0

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = list(map(double, numbers))
    evens = list(filter(is_even, numbers))
    print("Original:", numbers)
    print("Doubled:", doubled)
    print("Evens:", evens)
15 0 Open
Functions & basics easy

How to Pipe Data Through a List of Transform Functions in Python

Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.

functions functional reduce
Python
from functools import reduce

def pipe(data, *transforms):
    return reduce(lambda value, func: func(value), transforms, data)

def double(x):
    return x * 2

def add_one(x):
    return x + 1

def to_string(x):
    return f"Result: {x}"

if __name__ == "__main__":
    initial = 5
    result = pipe(initial, double, …
12 0 Open
Functions & basics easy

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.

ansicodes cli terminal
Python
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 _…
13 0 Open
Functions & basics easy

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.

environment-variables os configuration
Python
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
10 0 Open
Functions & basics easy

How to Return Multiple Values from a Python Function

This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.

functions tuple return-values
Python
def get_user_stats(name, score, level):
    """Return multiple values as a tuple."""
    return name, score, level

if __name__ == "__main__":
    result = get_user_stats("Alice", 95, 3)
    print(result)
    print(type(result))
    
    # Unpacking into individual variables
    player_name, player_score, player_level…
15 0 Open
Functions & basics easy

How to Sort a List of Dictionaries by Key with a Lambda in Python

Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.

sorting lambda dictionaries
Python
def get_students():
    return [
        {"name": "alice", "score": 85},
        {"name": "bob", "score": 92},
        {"name": "carol", "score": 78},
        {"name": "dave", "score": 92},
    ]

students = get_students()

sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
12 0 Open
Functions & basics easy

How to Sort a List of Numbers in Python with Default Parameters

Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.

sorting default-parameters functions
Python
def sort_numbers(numbers, reverse=False):
    """Sort a list of numbers in ascending or descending order."""
    return sorted(numbers, reverse=reverse)


def main():
    numbers = [5, 2, 9, 1, 7, 3]
    
    # Default sort (ascending)
    ascending = sort_numbers(numbers)
    print(f"Ascending: {ascending}")
    
   …
12 0 Open
Functions & basics easy

How to Use *args and **kwargs in Python Functions

Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.

args kwargs variadic
Python
def display_info(title, *args, **kwargs):
    """Display positional and keyword arguments received."""
    print(f"Title: {title}")
    print(f"Additional positional args ({len(args)}):")
    for i, arg in enumerate(args, 1):
        print(f"  {i}. {arg}")
    print(f"Keyword args ({len(kwargs)}):")
    for key, value…
13 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

if __name__ == "__main__":
    # Using defaults
    print(greet("Alice"))
    
    # Overriding first default
    print(greet("Bob", "Hi"))
    
    # Overrid…
13 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.

functions parameters defaults
Python
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")
12 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.

functions default-parameters comparison
Python
def compare(a, b, operation="equal"):
    if operation == "equal":
        return a == b
    elif operation == "greater":
        return a > b
    elif operation == "less":
        return a < b
    else:
        return f"Unknown operation: {operation}"

if __name__ == "__main__":
    print(compare(5, 5))
    print(com…
12 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Define a Python function with default parameters and call it using positional and keyword arguments.

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

if __name__ == "__main__":
    print(greet("Alice"))                 # Uses both defaults
    print(greet("Bob", "Hi"))             # Uses default punctua…
12 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Create a simple function with default parameters to build flexible, reusable greetings in Python.

functions default-parameters basics
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="?"))…
13 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.