Reference library

Functions & basics

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

3 matches
Functions & basics medium

How to Create a Counter Closure in Python

Build a closure in Python that remembers and increments a counter across calls without using global variables.

closures nonlocal state
Python
def create_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

if __name__ == "__main__":
    counter = create_counter(10)
    print(counter())
    print(counter())
    print(counter())
12 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

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.