Python Functions

Introduction to Functions

Functions encapsulate reusable logic. Use def to declare a function, grouping statements under a name:

def greet(name):
    print(f"Hello, {name}!")

# Calling the function
greet("Alice")  # Hello, Alice!

Docstrings

Document your functions using triple-quoted strings immediately after the def line:

def add(a, b):
    """Return the sum of a and b.

    Args:
        a (int): First number.
        b (int): Second number.

    Returns:
        int: Sum of a and b.
    """
    return a + b
 

Parameters & Arguments

Functions support:

  • Positional arguments
  • Default values: def fn(x, y=0)
  • Keyword-only args: def fn(*, flag=True)
  • Arbitrary args: *args and **kwargs
def combo(*args, **kwargs):
    print(args, kwargs)

combo(1,2, a=3, b=4)
 

Lambda Expressions

Anonymous functions using lambda for simple operations:

square = lambda x: x * x
print(square(5))  # 25
 

Decorators

Modify or wrap functions using decorators:

def timer(fn):
    import time
    def wrapper(*args, **kw):
        start = time.time()
        result = fn(*args, **kw)
        print(f"Elapsed: {time.time()-start:.4f}s")
        return result
    return wrapper

@timer
def compute(n):
    return sum(range(n))

compute(1000000)
 

Closures

Inner functions capturing outer scope variables:

def make_multiplier(m):
    def multiply(x):
        return x * m
    return multiply

double = make_multiplier(2)
print(double(5))  # 10