Reference library

Functions & basics

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

2 matches
Functions & basics easy

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.

functions composition lambda
Python
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…
12 0 Open
Functions & basics easy

How to Use a Dispatch Table in Python (Map Strings to Functions)

Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.

dispatch-table dictionary functions
Python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b


dispatch = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


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