def — Intermediate Examples
Defines a new function or method
*args and **kwargs
Accepting variable numbers of arguments.
python
def flexible(*args, **kwargs): print(f"Positional: {args}") print(f"Keyword: {kwargs}") flexible(1, 2, 3, name="Alice", age=30) def apply(func, *args, **kwargs): print(f"Calling {func.__name__}") return func(*args, **kwargs) result = apply(max, 3, 1, 4, 1, 5) print(f"Result: {result}")
*args captures extra positional arguments as a tuple. **kwargs captures extra keyword arguments as a dict. Together they let you write wrapper functions.
Closures
Functions that capture variables from their enclosing scope.
python
def make_multiplier(factor): def multiply(x): return x * factor return multiply double = make_multiplier(2) triple = make_multiplier(3) print(double(5)) print(triple(5)) print(double(triple(4)))
Expected Output
10 15 24
The inner function captures 'factor' from the enclosing scope. Each call to make_multiplier creates a new closure with its own captured value.
Want to try these examples interactively?
Open Intermediate Playground