Lesson 4 of 40
Foundations
Beginner
โฑ 30 min
Functions, Arguments & Closures
Write reusable functions with positional, keyword, *args, **kwargs, default arguments, closures, and first-class function patterns.
Part 1: Defining Functions
# Basic function with type hints
def greet(name: str, greeting: str = "Hello") -> str:
"""Return a formatted greeting string."""
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"
greet(name="Carol") # keyword arg
def greet(name: str, greeting: str = "Hello") -> str:
"""Return a formatted greeting string."""
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"
greet(name="Carol") # keyword arg
Part 2: *args and **kwargs
def total(*args: float) -> float:
return sum(args)
total(1, 2, 3, 4) # 10
def create_user(name: str, **kwargs):
print(f"User: {name}")
for k, v in kwargs.items():
print(f" {k}: {v}")
create_user("Alice", age=30, role="admin")
return sum(args)
total(1, 2, 3, 4) # 10
def create_user(name: str, **kwargs):
print(f"User: {name}")
for k, v in kwargs.items():
print(f" {k}: {v}")
create_user("Alice", age=30, role="admin")
Part 3: Lambda & Closures
# Lambda โ single-expression function
square = lambda x: x ** 2
sorted_names = sorted(names, key=lambda n: n.lower())
# Closure โ inner function captures outer variable
def make_multiplier(factor: int):
def multiply(x: int):
return x * factor # captures factor
return multiply
triple = make_multiplier(3)
triple(10) # 30
square = lambda x: x ** 2
sorted_names = sorted(names, key=lambda n: n.lower())
# Closure โ inner function captures outer variable
def make_multiplier(factor: int):
def multiply(x: int):
return x * factor # captures factor
return multiply
triple = make_multiplier(3)
triple(10) # 30
Part 4: Positional-Only & Keyword-Only Parameters
# / = positional-only * = keyword-only
def process(x, y, /, mode="fast", *, verbose=False):
"""x, y must be positional; verbose must be keyword."""
if verbose:
print(f"Processing ({x}, {y}) in {mode} mode")
process(1, 2, verbose=True) # โ
process(x=1, y=2) # โ TypeError
def process(x, y, /, mode="fast", *, verbose=False):
"""x, y must be positional; verbose must be keyword."""
if verbose:
print(f"Processing ({x}, {y}) in {mode} mode")
process(1, 2, verbose=True) # โ
process(x=1, y=2) # โ TypeError
๐ Want the complete guide with projects?
Get the book โ