Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Samacheer Kalvi 12th Computer Science Chapter 7 Python Functions Exercise Solutions | KalviGavani

Complete TN State Board Class 12 Computer Science Chapter 7 Python Functions exercise solutions — defining functions, arguments, default arguments, keyword arguments, *args, **kwargs, recursion, lambda, map/filter/reduce, docstrings, return values with code examples.

Updated 13 June 202610 min read

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

ConceptSyntaxPurpose
Defining a functiondef name(params):Create a reusable block of code
Calling a functionname(args)Execute the function
return statementreturn valueSend a result back to the caller
Default argumentdef f(x, y=10):Parameter with a preset value
Keyword argumentf(x=5, y=20)Pass arguments by name
*argsdef f(*args):Collect extra positional arguments into a tuple
**kwargsdef f(**kwargs):Collect extra keyword arguments into a dict
Docstring"""doc text"""Document what the function does
RecursionFunction calling itselfSolve problems by breaking into sub-problems
Lambdalambda x: x*xAnonymous single-expression function
mapmap(func, iterable)Apply function to every item
filterfilter(func, iterable)Keep items where function returns True
reducereduce(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
Answer(b) def

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
Answer(c) a = 3, b uses default value 5, so 3 + 5 = 8.

Q3. What does *args produce inside a function?

  • (a) A list
  • (b) A dictionary
  • (c) A tuple
  • (d) A set
Answer(c) *args collects all extra positional arguments into a tuple.

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
Answer(a) 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
Answer(b) Without a base case, the function calls itself endlessly until Python raises a RecursionError.

Fill in the Blanks

Q1. The ______ statement is used to send a value back from a function to the caller.

Answerreturn

Q2. A function that calls itself is called a ______ function.

Answerrecursive

Q3. ______ arguments are passed by specifying the parameter name during the function call.

AnswerKeyword (or named)

Q4. The built-in function ______ returns the number of arguments passed to it when used with *args.

Answerlen (used as len(args))

Q5. lambda x, y: x + y is an example of an ______ function.

Answeranonymous (or lambda)

True or False

Q1. A Python function can return multiple values.

AnswerTrue — Python returns multiple values as a tuple. Example: return a, b returns the tuple (a, b).

Q2. Default arguments must appear after non-default arguments in the function definition.

AnswerTrue — def f(a, b=5) is valid; def f(a=5, b) is a SyntaxError.

Q3. **kwargs stores keyword arguments as a list.

AnswerFalse — **kwargs stores keyword arguments as a dictionary.

Q4. A lambda function can contain multiple statements.

AnswerFalse — A lambda is limited to a single expression.

Q5. The map() function modifies the original iterable.

AnswerFalse — map() returns a new map object; the original iterable is unchanged.

Match the Following

Column AColumn 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
Answer1-c, 2-d, 3-b, 4-e, 5-a

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
CollectsExtra positional argumentsExtra keyword arguments
Data typeTupleDictionary
Syntax in callf(1, 2, 3)f(a=1, b=2)
AccessIndex 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

MistakeWhy It's WrongCorrection
Missing return statementFunction returns None instead of a valueAlways use return when the function must produce a result
Default argument before non-defaultdef f(a=5, b): is a SyntaxErrorPlace default args after non-default: def f(b, a=5):
No base case in recursionCauses infinite recursion → RecursionErrorAlways include a terminating condition
Mutable default argument (def f(lst=[]):)The same list is reused across callsUse def f(lst=None): and assign inside
Using = instead of == in conditions= is assignment, not comparisonUse == for comparison inside function logic
Forgetting from functools import reducereduce is not a built-in in Python 3Import it before using
Calling lambda with wrong number of argslambda x: x+1 expects 1 argumentMatch the number of arguments to the lambda signature

Exam Checklist

  • [ ] I can define and call functions with positional, keyword, and default arguments
  • [ ] I understand args and *kwargs and 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(), and reduce() with lambda
  • [ ] I can write docstrings and access them using __doc__
  • [ ] I understand the difference between return and print inside functions
  • [ ] I can trace recursive calls and predict outputs

Frequently Asked Questions

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. They allow functions to accept a variable number of arguments.
← Browse all Class 12 Exercise Solutions

Other question types — same chapter