Python Functions: Everything You Need to Know for Your Exam
Functions are the backbone of every Python program. Here's what exams actually test — from default argument traps to how *args and **kwargs work.
Defining and calling functions
A function is defined with `def`, accepts parameters, and returns a value with `return`. If there's no `return` statement, the function returns `None`.
def greet(name):
return f"Hello, {name}"
result = greet("Alice") # "Hello, Alice"
def do_nothing():
pass
print(do_nothing()) # NoneDefault arguments — and the mutable default trap
Default argument values are evaluated once when the function is defined, not each time it's called. This creates a well-known trap with mutable defaults like lists.
# TRAP — default list is shared across all calls
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] — NOT [2]
# FIX — use None as default
def add_item_safe(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst*args and **kwargs
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Both names are conventions — only the * and ** matter.
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
def profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
profile(name="Alice", age=30)
# name: Alice
# age: 30Argument order matters
When mixing argument types, they must appear in this order: positional → *args → keyword-only → **kwargs. Getting this wrong causes a SyntaxError.
def example(a, b, *args, keyword_only, **kwargs):
pass
# Calling it correctly:
example(1, 2, 3, 4, keyword_only="required", extra="ok")Lambda functions
A lambda is a one-line anonymous function. It can take any number of arguments but only a single expression — no statements, no assignments.
double = lambda x: x * 2 print(double(5)) # 10 # Often used with sorted(), filter(), map() names = ["Charlie", "Alice", "Bob"] sorted_names = sorted(names, key=lambda n: len(n)) # ["Bob", "Alice", "Charlie"]
Exam tip
The most common Python functions question involves mutable default arguments. If you see `def f(x, lst=[])` in an exam question, the answer almost always involves shared state across calls.
Think you're ready? Prove it.
Take the free Python readiness test. Get a score, topic breakdown, and your exact weak areas.
Take the free Python test →Free · No sign-up · Instant results