Functions are the basic unit of reuse in Python, but the language packs a surprising amount of flexibility into them. Here's a tour beyond the basics.
The Fundamentals
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", greeting="Hi") # "Hi, Bob!"
Default arguments, keyword arguments, and positional arguments all combine to make function calls flexible and readable.
Functions Are Objects
In Python, functions are first-class citizens — they can be assigned to variables, passed as arguments, and returned from other functions.
def square(x):
return x * x
operation = square
print(operation(5)) # 25
def apply(func, value):
return func(value)
print(apply(square, 4)) # 16
This is the foundation for decorators, callbacks, and functional-style code.
*args and **kwargs
These let a function accept an arbitrary number of positional or keyword arguments:
def summarize(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
summarize(1, 2, 3, name="Alice", age=30)
# Positional: (1, 2, 3)
# Keyword: {'name': 'Alice', 'age': 30}
This pattern is common in wrapper functions and libraries that need to forward arguments.
Lambda Functions
For small, throwaway functions, lambda provides a compact syntax:
numbers = [5, 2, 8, 1]
sorted_numbers = sorted(numbers, key=lambda x: -x)
Lambdas are limited to a single expression — for anything more complex, a regular def is clearer.
Closures
A function can "remember" variables from the scope in which it was defined:
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
Here, multiplier closes over factor, retaining access to it long after make_multiplier has finished running.
Type Hints
Modern Python supports optional type annotations for clarity and tooling support:
def add(a: int, b: int) -> int:
return a + b
These aren't enforced at runtime but are invaluable for readability and catching bugs with tools like mypy.
Key Takeaway
Functions in Python aren't just reusable blocks of code — they're objects you can pass around, compose, and customize with defaults, variadic arguments, and closures. Understanding this flexibility is what unlocks patterns like decorators and functional programming later on.
Comments (0)
No comments yet
Be the first to share your thoughts!