💻
Chapter 2 · Class 12 Computer Science
Functions and Recursion
1 exercises3 questions solved
Exercise 2.1Functions and Recursion in Python
Q1
What is a function in Python? Explain the types of arguments that can be passed to a function.
Solution
Function:
• A function is a named, reusable block of code that performs a specific task.
• Functions promote code reuse, modularity, and readability.
• Syntax:
def function_name(parameters):
# body
return value
Types of Arguments in Python:
1. Positional (Required) Arguments:
• Arguments passed in the same order as parameters defined.
• All required parameters must be provided.
• Example:
def greet(name, age):
print(f'Hello {name}, you are {age} years old.')
greet('Priya', 17) # name='Priya', age=17
2. Default Arguments:
• A parameter has a default value — caller may omit it.
• Default parameters must come after non-default ones.
• Example:
def greet(name, age=18):
print(f'{name} is {age}')
greet('Ravi') # age defaults to 18
greet('Meena', 16) # age is 16
3. Keyword (Named) Arguments:
• Caller specifies parameter names explicitly — order does not matter.
• Example:
def book(title, author, year):
print(title, author, year)
book(author='Tagore', year=1910, title='Gitanjali')
4. Variable-length Positional Arguments (*args):
• Accepts an arbitrary number of positional arguments — packed into a tuple.
• Example:
def total(*nums):
return sum(nums)
total(1, 2, 3, 4) # → 10
5. Variable-length Keyword Arguments (**kwargs):
• Accepts an arbitrary number of keyword arguments — packed into a dictionary.
• Example:
def display(**info):
for k, v in info.items():
print(k, ':', v)
display(name='Arjun', city='Delhi', marks=95)
Scope: Variables defined inside a function are local (not accessible outside). Global variables can be accessed inside a function but must be declared global to be modified.
Q2
What is recursion? Write a Python function to compute the factorial of a number using recursion. What are its advantages and disadvantages?
Solution
Recursion:
• Recursion is a programming technique where a function calls itself to solve a smaller instance of the same problem.
• Every recursive function must have:
1. Base case: A condition at which the function stops calling itself and returns a result directly.
2. Recursive case: The function calls itself with a simpler/smaller input, moving toward the base case.
Recursive Factorial Function:
• Definition: n! = n × (n-1)! for n > 0, and 0! = 1 (base case)
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case
print(factorial(5)) # Output: 120
Call stack trace for factorial(4):
factorial(4) → 4 × factorial(3)
→ 4 × 3 × factorial(2)
→ 4 × 3 × 2 × factorial(1)
→ 4 × 3 × 2 × 1 (base case reached)
→ 24
Another example — Fibonacci using recursion:
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
Advantages of Recursion:
1. Elegant and clean code — complex problems (tree traversal, divide-and-conquer) expressed naturally.
2. Reduces code length for problems with recursive structure.
3. Direct translation of mathematical definitions (factorial, Fibonacci).
Disadvantages of Recursion:
1. Performance overhead: Each function call uses stack memory — deep recursion can cause a stack overflow.
2. Slower than iteration: Repeated function calls have overhead (stack frame creation/destruction).
3. Recomputation: Naive recursion may recompute the same subproblems many times (e.g., Fibonacci without memoisation).
4. Harder to debug: Recursive call chains can be difficult to trace.
Q3
What are Python's built-in functions? Explain any ten important built-in functions with examples.
Solution
Python comes with many built-in functions available without any import.
1. len(obj):
• Returns the number of items in a sequence or collection.
• len('hello') → 5; len([1, 2, 3]) → 3
2. type(obj):
• Returns the type of an object.
• type(3.14) → <class 'float'>; type([]) → <class 'list'>
3. int(), float(), str(), bool():
• Type conversion functions.
• int('42') → 42; float(5) → 5.0; str(100) → '100'
4. input(prompt):
• Reads a string from the user.
• name = input('Enter name: ')
5. print(*objects, sep=' ', end='\n'):
• Outputs to console.
• print('Hi', 'there', sep='-') → Hi-there
6. range(start, stop, step):
• Generates a sequence of numbers.
• list(range(1, 10, 2)) → [1, 3, 5, 7, 9]
7. sorted(iterable, reverse=False):
• Returns a new sorted list.
• sorted([3, 1, 4, 1, 5]) → [1, 1, 3, 4, 5]
• sorted('banana') → ['a', 'a', 'a', 'b', 'n', 'n']
8. max() and min():
• Return the largest/smallest item.
• max([10, 3, 25, 7]) → 25; min('a', 'z', 'k') → 'a'
9. abs(x):
• Returns the absolute value.
• abs(-15) → 15; abs(-3.7) → 3.7
10. enumerate(iterable, start=0):
• Returns an iterator of (index, value) pairs.
• for i, v in enumerate(['a', 'b', 'c']): print(i, v)
→ 0 a, 1 b, 2 c
11. zip(*iterables):
• Combines multiple iterables element-by-element.
• list(zip([1,2,3], ['a','b','c'])) → [(1,'a'),(2,'b'),(3,'c')]
12. map(function, iterable):
• Applies a function to every item in an iterable.
• list(map(str, [1, 2, 3])) → ['1', '2', '3']
More chapters
← All chapters: Class 12 Computer Science