How to Use This Page
1. Attempt every exercise on your own before reading the solution. 2. Compare your approach with the solution — focus on the logic, not just the final answer. 3. Type and run the Python code on your computer; reading alone is not enough. 4. Review the Common Mistakes section to avoid errors that cost marks in exams.
Key Concepts
| Concept | Syntax | Purpose |
|---|---|---|
| Defining a function | def name(params): | Create a reusable block of code |
| Calling a function | name(args) | Execute the function |
| return statement | return value | Send a result back to the caller |
| Default argument | def f(x, y=10): | Parameter with a preset value |
| Keyword argument | f(x=5, y=20) | Pass arguments by name |
| *args | def f(*args): | Collect extra positional arguments into a tuple |
| **kwargs | def f(**kwargs): | Collect extra keyword arguments into a dict |
| Docstring | """doc text""" | Document what the function does |
| Recursion | Function calling itself | Solve problems by breaking into sub-problems |
| Lambda | lambda x: x*x | Anonymous single-expression function |
| map | map(func, iterable) | Apply function to every item |
| filter | filter(func, iterable) | Keep items where function returns True |
| reduce | reduce(func, iterable) | Reduce iterable to a single value |
Multiple Choice Questions (MCQs)
Q1. Which keyword is used to define a function in Python?
- (a) function
- (b) def
- (c) func
- (d) define
Q2. What is the output of the following code?
def add(a, b=5):
return a + b
print(add(3))
- (a) 3
- (b) 5
- (c) 8
- (d) Error
Q3. What does *args produce inside a function?
- (a) A list
- (b) A dictionary
- (c) A tuple
- (d) A set
Q4. Which of the following is a valid lambda function to square a number?
- (a)
lambda x: x**2 - (b)
lambda(x){return x**2} - (c)
def lambda x: x**2 - (d)
lambda x -> x**2
Q5. What happens if a recursive function has no base case?
- (a) Returns 0
- (b) Infinite recursion → RecursionError
- (c) Returns None
- (d) Executes once
Fill in the Blanks
Q1. The ______ statement is used to send a value back from a function to the caller.
Q2. A function that calls itself is called a ______ function.
Q3. ______ arguments are passed by specifying the parameter name during the function call.
Q4. The built-in function ______ returns the number of arguments passed to it when used with *args.
Q5. lambda x, y: x + y is an example of an ______ function.
True or False
Q1. A Python function can return multiple values.
Q2. Default arguments must appear after non-default arguments in the function definition.
Q3. **kwargs stores keyword arguments as a list.
Q4. A lambda function can contain multiple statements.
Q5. The map() function modifies the original iterable.
Match the Following
| Column A | Column B |
|---|---|
| 1. def | (a) Anonymous single-expression function |
| 2. return | (b) Collects positional arguments into tuple |
| 3. *args | (c) Keyword to define a function |
| 4. **kwargs | (d) Sends value back to caller |
| 5. lambda | (e) Collects keyword arguments into dict |
Short Answer Questions
Q1. What is a function? What are its advantages?
A function is a named block of reusable code that performs a specific task.
Advantages:
- Reusability — Write once, call many times
- Modularity — Breaks large programs into smaller parts
- Readability — Named functions make code self-documenting
- Debugging — Easier to test and fix isolated functions
- Avoids repetition — No need to duplicate code
Q2. Explain default arguments with an example.
Default arguments allow parameters to have preset values. If no argument is passed, the default is used.
def greet(name, msg="Hello"):
print(msg, name)
greet("Arun") # Hello Arun (msg uses default)
greet("Arun", "Welcome") # Welcome Arun (msg is overridden)
Q3. Differentiate between args and *kwargs.
| Feature | *args | **kwargs |
|---|---|---|
| Collects | Extra positional arguments | Extra keyword arguments |
| Data type | Tuple | Dictionary |
| Syntax in call | f(1, 2, 3) | f(a=1, b=2) |
| Access | Index args[0] | Key kwargs["a"] |
def show(*args, **kwargs):
print(args) # (1, 2, 3)
print(kwargs) # {'x': 10, 'y': 20}
show(1, 2, 3, x=10, y=20)
Q4. What is a lambda function? Give two examples.
A lambda is an anonymous, single-expression function.
# Square a number
square = lambda x: x ** 2
print(square(5)) # 25
# Add two numbers
add = lambda a, b: a + b
print(add(3, 4)) # 7
Q5. What is a docstring? How is it written?
A docstring is a string literal placed right after the function definition line to document what the function does. It is accessed using function_name.__doc__.
def area(length, breadth):
"""Calculates the area of a rectangle."""
return length * breadth
print(area.__doc__) # Calculates the area of a rectangle.
Detailed Answers
Q1. Explain the different types of function arguments in Python with examples.
Python supports four types of arguments:
(a) Positional Arguments
Arguments passed in order; parameters matched by position.
def detail(name, age):
print(name, "is", age, "years old")
detail("Arun", 17) # Arun is 17 years old
(b) Keyword Arguments
Arguments passed by specifying the parameter name; order does not matter.
def detail(name, age):
print(name, "is", age, "years old")
detail(age=17, name="Arun") # Arun is 17 years old
(c) Default Arguments
Parameters with preset values; used when no argument is passed.
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 (exp defaults to 2)
print(power(5, 3)) # 125 (exp is 3)
(d) Variable-Length Arguments
*Using args (positional):**
def total(*marks):
return sum(marks)
print(total(80, 90, 75, 85)) # 330
Using kwargs (keyword):**
def display(**info):
for key, value in info.items():
print(key, ":", value)
display(name="Arun", age=17, city="Chennai")
# name : Arun
# age : 17
# city : Chennai
Q2. Write a recursive function to find the factorial of a number. Explain each step.
def factorial(n):
"""Returns factorial of n using recursion."""
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # 120
Trace for factorial(5):
factorial(5)= 5 ×factorial(4)factorial(4)= 4 ×factorial(3)factorial(3)= 3 ×factorial(2)factorial(2)= 2 ×factorial(1)factorial(1)= 1 (base case reached)- Unwinding: 1 → 2 → 6 → 24 → 120
Q3. Write a recursive function to find the nth Fibonacci number.
def fibonacci(n):
"""Returns the nth Fibonacci number."""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(8):
print(fibonacci(i), end=" ")
# Output: 0 1 1 2 3 5 8 13
Q4. Explain map(), filter(), and reduce() with examples.
map() — Apply a function to every item
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
filter() — Keep items that satisfy a condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8]
reduce() — Reduce to a single value (needs import)
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
Q5. Write a function that accepts args and *kwargs and displays them.
def student_info(*args, **kwargs):
print("Positional arguments (args):", args)
print("Keyword arguments (kwargs):", kwargs)
student_info("Arun", "XII", age=17, city="Chennai")
# Positional arguments (args): ('Arun', 'XII')
# Keyword arguments (kwargs): {'age': 17, 'city': 'Chennai'}
Q6. Write a function to check whether a string is a palindrome using recursion.
def is_palindrome(s):
"""Checks if string s is a palindrome using recursion."""
s = s.lower().replace(" ", "") # normalize
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("madam")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("racecar")) # True
Q7. Write a program using lambda and map to convert a list of temperatures from Celsius to Fahrenheit.
celsius = [0, 10, 20, 30, 40, 50]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print("Celsius: ", celsius)
print("Fahrenheit:", fahrenheit)
# Celsius: [0, 10, 20, 30, 40, 50]
# Fahrenheit: [32.0, 50.0, 68.0, 86.0, 104.0, 122.0]
Common Mistakes
| Mistake | Why It's Wrong | Correction |
|---|---|---|
Missing return statement | Function returns None instead of a value | Always use return when the function must produce a result |
| Default argument before non-default | def f(a=5, b): is a SyntaxError | Place default args after non-default: def f(b, a=5): |
| No base case in recursion | Causes infinite recursion → RecursionError | Always include a terminating condition |
Mutable default argument (def f(lst=[]):) | The same list is reused across calls | Use def f(lst=None): and assign inside |
Using = instead of == in conditions | = is assignment, not comparison | Use == for comparison inside function logic |
Forgetting from functools import reduce | reduce is not a built-in in Python 3 | Import it before using |
| Calling lambda with wrong number of args | lambda x: x+1 expects 1 argument | Match the number of arguments to the lambda signature |
Exam Checklist
- [ ] I can define and call functions with positional, keyword, and default arguments
- [ ] I understand
argsand*kwargsand can write functions that use them - [ ] I can write recursive functions with a proper base case
- [ ] I can write and use lambda functions
- [ ] I can use
map(),filter(), andreduce()with lambda - [ ] I can write docstrings and access them using
__doc__ - [ ] I understand the difference between
returnandprintinside functions - [ ] I can trace recursive calls and predict outputs
