Functions in Python
Defining functions, arguments, *args/**kwargs, lambda, map, filter, and decorators.
What You Will Learn in Functions in Python
Functions in Python are first-class objects defined with `def`, supporting default arguments, *args, **kwargs, lambda expressions, and decorators.
- Default parameters: `def greet(name, msg='Hello')` — must follow positional args.
- *args: collects extra positional arguments as a tuple. **kwargs: collects extra keyword arguments as a dict.
- Lambda: anonymous single-expression function — `square = lambda x: x**2`.
- Closures: inner function accessing outer function's scope, even after outer returns.
- Decorators: functions that modify/wrap other functions, applied with `@decorator` syntax.
- Generators: `yield` instead of `return` — lazy evaluation for memory efficiency.
Syntax
def function_name(pos_arg, default_arg=val, *args, **kwargs):
"""Docstring"""
# function body
return value
# Lambda
f = lambda x, y: x + y
# Decorator
def decorator(func):
def wrapper(*args, **kwargs):
# before
result = func(*args, **kwargs)
# after
return result
return wrapperComplete Code Example
# Closure example
def make_multiplier(n):
def multiplier(x):
return x * n # 'n' is from outer scope
return multiplier
triple = make_multiplier(3)
print(triple(5)) # 15
# Decorator example
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"Done. Result: {result}")
return result
return wrapper
@logger
def add(a, b): return a + b
add(3, 4)
# Calling add
# Done. Result: 7Example
`sorted(students, key=lambda s: s['marks'], reverse=True)` sorts students by marks using a lambda.
Expected Exam Questions — Functions in Python
Q1.What is the difference between `*args` and `**kwargs`?
Q2.What is a Python generator? When should you use one?
Q3.What is a closure in Python?
🔘 MCQ Practice — Functions in Python
MCQ 1.What does `lambda x: x**2` create?
✓ Correct Answer: An anonymous function
MCQ 2.Which statement is correct about `yield` in Python?
✓ Correct Answer: It returns a value and suspends the function state
Download Functions in Python PDF Notes
Get the complete Functions in Python notes as a PDF — free for enrolled students, or browse our public study materials library.