Back to Python Programming
🐍Python Programming

Functions in Python

Defining functions, arguments, *args/**kwargs, lambda, map, filter, and decorators.

BeginnerIntermediateAdvanced

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 wrapper

Complete 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: 7

Example

`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`?
Answer: `*args` collects extra positional arguments into a tuple: `def f(*args): print(args)`. `**kwargs` collects extra keyword arguments into a dict: `def f(**kwargs): print(kwargs)`. They can be combined: `def f(a, *args, **kwargs)`.
Q2.What is a Python generator? When should you use one?
Answer: A generator is a function using `yield` that returns an iterator, producing values lazily (one at a time). Use when dealing with large datasets to avoid loading everything into memory: `def count(): for i in range(10**9): yield i`.
Q3.What is a closure in Python?
Answer: A closure is an inner function that remembers variables from its enclosing scope even after the outer function has finished executing. It is created when a nested function references variables from the enclosing function.

🔘 MCQ Practice — Functions in Python

MCQ 1.What does `lambda x: x**2` create?
A. A class
B. An anonymous function
C. A decorator
D. A generator

✓ Correct Answer: An anonymous function

MCQ 2.Which statement is correct about `yield` in Python?
A. It terminates the function
B. It returns a value and suspends the function state
C. It is used for exception handling
D. It creates a class method

✓ 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.

More Python Programming Topics

Related Subjects

Frequently Asked Questions — Functions in Python

What is Functions in Python in Python Programming?
Functions in Python are first-class objects defined with `def`, supporting default arguments, *args, **kwargs, lambda expressions, and decorators.
What is the difference between `*args` and `**kwargs`?
`*args` collects extra positional arguments into a tuple: `def f(*args): print(args)`. `**kwargs` collects extra keyword arguments into a dict: `def f(**kwargs): print(kwargs)`. They can be combined: `def f(a, *args, **kwargs)`.
What is a Python generator? When should you use one?
A generator is a function using `yield` that returns an iterator, producing values lazily (one at a time). Use when dealing with large datasets to avoid loading everything into memory: `def count(): for i in range(10**9): yield i`.
What is a closure in Python?
A closure is an inner function that remembers variables from its enclosing scope even after the outer function has finished executing. It is created when a nested function references variables from the enclosing function.
How do I prepare Functions in Python for exams?
To master Functions in Python, start by reading the theory carefully, then go through solved examples step by step. Practice numericals (if applicable), revise key formulas, and attempt previous year questions. SII notes cover all these aspects in a structured manner.
Are these Functions in Python notes free?
Yes! SII provides free access to Functions in Python notes and introductory study materials. Enrolled students get full access to detailed notes, solved papers, and live doubt-clearing sessions.
Which exams ask questions from Functions in Python?
Functions in Python is an important topic tested in Beginner, Intermediate, Advanced board exams, as well as GATE (CS & IT), University Semester Exams. It frequently appears in both short-answer and long-answer sections.