Skip to content

Functions, nested functions, and closures [ref]

Problem

  • Define and call a function adding 2 and 3.
  • Define a function with default step = 1; call it for 5 with and without an explicit step of 3.
  • Return a nested function capturing 10, then call it with 3.
  • Increment an enclosing integer twice from a nested function using nonlocal.
  • Append to an enclosing list from a nested function without nonlocal.

Python solution

def add(a, b):
    return a + b

add(2, 3)  # 5

def advance(value, step=1):
    return value + step

advance(5)     # 6
advance(5, 3)  # 8

def make_adder(amount):
    def add_amount(value):
        return value + amount
    return add_amount

make_adder(10)(3)  # 13

def count_twice():
    count = 0
    def visit():
        nonlocal count
        count += 1
    visit()
    visit()
    return count

count_twice()  # 2

def collect():
    values = []
    def visit():
        values.append(1)
    visit()
    return values

collect()  # [1]