Functions

Recursion

Recursive functions solve nested problems by calling themselves on smaller pieces.

A recursive function calls itself to solve a smaller piece of the same problem. Recursion exists for data that is naturally nested: trees, menus, expression nodes, and directory-like structures.

Every recursive function needs a base case that can be answered directly. The recursive case must move toward that base case by passing a smaller part of the data.

Prefer loops for simple repetition over a flat sequence. Prefer recursion when the data shape is recursive too.

A leaf node is the base case. It has no children, so the function can return its own value without making another recursive call.

Source

def total(node):
    subtotal = node["value"]
    for child in node["children"]:
        subtotal += total(child)
    return subtotal

print(total({"value": 2, "children": []}))

Output

2

A non-leaf node solves the same problem for each child, then combines those smaller totals with its own value.

Source

tree = {
    "value": 1,
    "children": [
        {"value": 2, "children": []},
        {"value": 3, "children": [{"value": 4, "children": []}]},
    ],
}

print(total(tree))

Output

10
At the leaf with value 4, three frames of total are stacked, each waiting on the one below; unwinding returns 4, then 3 + 4 = 7, then 1 + 2 + 7 = 10.

Notes

See also

Run the complete example

Example code

Expected output

2
10

Execution time appears here after you run the example.