Current Affairs updated daily
KalviGavaniKalviGavani

Functions and Modules Exercise Solutions | KalviGavani

TN Class 11 CS Functions and Modules exercise solutions — function definition, parameters, return values, recursion, built-in and user-defined modules with code.

Updated 15 June 202617 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

Functions and Modules — TN Class 11 CS Exercise Solutions

Complete exercise solutions for the Tamil Nadu Board Class 11 Computer Science chapter Functions and Modules. Covers function definition, parameters, return values, scope, recursion, and Python modules with working code.


How to Use This Page

1. Attempt each exercise on your own first — write function definitions before checking solutions. 2. Run every code example in IDLE or a Python editor to verify output. 3. Understand parameter passing — trace how arguments map to parameters. 4. Practise writing modules — create separate .py files and import them. 5. Focus on recursion — always identify the base case first, then the recursive case.


Key Concepts (Quick Recap)

ConceptSyntaxDetails
Function definitiondef name(params):Named, reusable block of code
Function callname(args)Executes the function with given arguments
ParametersVariables in function definitionPlaceholders for input values
ArgumentsValues passed during callActual data sent to the function
Return statementreturn valueSends a result back to the caller; ends the function
Default parameterdef f(x, y=10):Parameter with a default value if not provided
Local variableInside functionAccessible only within that function
Global variableOutside all functionsAccessible everywhere (use global keyword to modify inside functions)
RecursionFunction calls itselfMust have base case (stop) and recursive case
Module.py file with functionsImported using import, from...import
import mathimport mathAccess: math.sqrt(16)
from math import sqrtImport specific functionAccess: sqrt(16) directly
math.piConstant3.141592653589793
math.sqrt(x)Square rootReturns float
math.pow(x, y)x raised to yReturns float
math.ceil(x)Round upceil(4.2) = 5
math.floor(x)Round downfloor(4.8) = 4
random.randint(a, b)Random integerInclusive of both a and b
random.choice(seq)Random itemFrom a sequence

Code Examples:

# Simple function
def greet():
    print("Hello, Student!")

greet()  # Function call

# Function with parameters
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

# Function with default parameter
def power(base, exp=2):
    return base ** exp

print(power(5))    # 25 (uses default exp=2)
print(power(5, 3)) # 125 (uses exp=3)

# Function with return value
def area_circle(radius):
    return 3.14159 * radius * radius

print(area_circle(5))  # Output: 78.53975
# Using math module
import math
print(math.sqrt(25))    # 5.0
print(math.pi)          # 3.141592653589793
print(math.ceil(4.2))   # 5
print(math.floor(4.8))  # 4

# Using random module
import random
print(random.randint(1, 10))  # Random integer 1-10
print(random.choice(["a", "b", "c"]))  # Random item

I. Choose the Best Answer (MCQs)

Q1. The keyword used to define a function in Python is: (a) function (b) def (c) func (d) define

Answer(b) def

In Python, functions are defined using the def keyword followed by the function name and parameters in parentheses.


Q2. What is the output of the following code?
def greet(name="World"):
    print("Hello", name)
greet("Python")
Answer

(a) Hello World (b) Hello Python (c) Error (d) None

Answer(b) Hello Python

When a function is called with an argument, the argument value replaces the default value. "Python" is passed, so it prints "Hello Python".


Q3. A variable defined inside a function is called a: (a) Global variable (b) Local variable (c) Static variable (d) Constant

Answer(b) Local variable

A variable defined inside a function is local to that function — it cannot be accessed from outside the function.


Q4. The return statement in a function: (a) Prints a value (b) Sends a value back to the caller and ends the function (c) Continues the function (d) Defines a variable

Answer(b) Sends a value back to the caller and ends the function

The return statement sends a result to the calling code and immediately exits the function. Any code after return is not executed.


Q5. Which module is used to generate random numbers in Python? (a) math (b) sys (c) random (d) os

Answer(c) random

The random module provides functions like random.randint(), random.random(), and random.choice() for generating random numbers and selections.


Q6. What will math.floor(3.7) return? (a) 3.7 (b) 4 (c) 3 (d) 3.0

Answer(c) 3

math.floor() returns the largest integer less than or equal to the given number. floor(3.7) = 3.


Q7. Recursion is when: (a) A function calls another function (b) A function calls itself (c) A loop repeats (d) A module is imported

Answer(b) A function calls itself

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem. It must have a base case to stop the recursion.


II. Fill in the Blanks

1. The keyword used to define a function in Python is def. 2. A variable defined outside all functions is called a global variable. 3. The return statement sends a value back from a function to the caller. 4. A function that calls itself is called a recursive function. 5. The math module provides mathematical functions like sqrt(), ceil(), and floor(). 6. To import a specific function from a module, we use the from keyword (e.g., from math import sqrt). 7. Parameters with default values are called default parameters. 8. The random.randint(1, 6) function generates a random integer between 1 and 6 (inclusive). 9. A variable defined inside a function is called a local variable. 10. The math.pi constant gives the value of 3.141592653589793. 11. A function that does not return a value returns None by default. 12. The math.ceil(4.2) function returns 5. 13. The math.floor(4.8) function returns 4. 14. The random module is used to generate random numbers and make random selections.


III. True or False (with corrections for false statements)

Q1. A function in Python must always return a value.
Answer

False. A function in Python does not have to return a value. If no return statement is present, the function returns None by default.


Q2. A local variable can be accessed from outside the function.
Answer

False. A local variable is accessible only within the function where it is defined. It cannot be accessed from outside.


Q3. The import math statement imports all functions from the math module.
Answer

True. import math makes all functions and constants in the math module available, accessed as math.function_name().


Q4. Default parameters must come after non-default parameters in a function definition.
Answer

True. In Python, parameters with default values must be placed after parameters without default values. def f(a, b=5) is valid; def f(a=5, b) is not.


Q5. The math.sqrt() function returns an integer.
Answer

False. math.sqrt() always returns a float, even if the result is a perfect square. For example, math.sqrt(25) returns 5.0, not 5.


Q6. Recursive functions must have a base case to stop recursion.
Answer

True. Without a base case, the function calls itself infinitely, eventually causing a RecursionError. The base case provides the condition to stop recursion.


Q7. The from math import * statement imports only the sqrt function.
Answer

False. The * wildcard imports all functions and constants from the module. from math import sqrt would import only the sqrt function.


IV. Match the Following

Column AColumn B
1. def(c) Define a function
2. return(e) Send value back to caller
3. import(a) Load a module
4. math.sqrt()(d) Square root function
5. random.randint()(f) Random integer in range
6. math.pi(b) Value of π
Answer1–c, 2–e, 3–a, 4–d, 5–f, 6–b

Column AColumn B
1. Local variable(d) Accessible only inside the function
2. Global variable(a) Accessible everywhere
3. Parameter(b) Variable in function definition
4. Argument(e) Value passed during function call
5. Default parameter(c) Parameter with a preset value
6. Recursion(f) Function calling itself
Answer1–d, 2–a, 3–b, 4–e, 5–c, 6–f

V. Answer Briefly (2-Mark Questions)

Q1. What is a function? Write a simple function to greet a user.
Answer

A function is a named, reusable block of code that performs a specific task. Functions help organise code, avoid repetition, and make programs easier to read and debug.

def greet(name):
    print("Hello,", name + "! Welcome to Python.")

greet("Ravi")   # Output: Hello, Ravi! Welcome to Python.
greet("Priya")  # Output: Hello, Priya! Welcome to Python.

Q2. Differentiate between parameters and arguments.
Answer
FeatureParameterArgument
DefinitionVariable in function definitionActual value passed during call
PositionIn def add(a, b): — a and b are parametersIn add(5, 3) — 5 and 3 are arguments
Also calledFormal parameterActual parameter
When definedWhen the function is definedWhen the function is called
def add(a, b):   # a, b are parameters
    return a + b

result = add(5, 3)   # 5, 3 are arguments

Q3. What is a module? How do you import a module?
Answer

A module is a Python file (.py) containing functions, classes, and variables that can be reused in other programs.

Three ways to import a module:

# Method 1: Import entire module
import math
print(math.sqrt(25))  # Access with module prefix

# Method 2: Import specific function
from math import sqrt
print(sqrt(25))       # No prefix needed

# Method 3: Import everything
from math import *
print(pi)             # All names available directly

Q4. What is the difference between local and global variables?
Answer
FeatureLocal VariableGlobal Variable
DefinedInside a functionOutside all functions
ScopeOnly within that functionEntire program
AccessCannot be accessed outside the functionCan be accessed anywhere
LifetimeExists only while function executesExists throughout program execution
x = 10  # Global variable

def my_function():
    y = 5  # Local variable
    print("Inside:", x, y)  # Can access both x and y

my_function()
print("Outside:", x)  # Can access x
# print(y)  # Error! y is not defined outside the function

VI. Answer in Detail (5-Mark Questions)

Q1. Explain functions in Python with types, syntax, and examples. Write a program using a function to find the factorial of a number.
Answer

Function Definition: A function is a named block of reusable code that performs a specific task. It helps in:

  • Code reusability (write once, use many times)
  • Modularity (break complex programs into smaller parts)
  • Readability (easier to understand)

Types of Functions:

TypeDescriptionExample
Built-inPredefined in Pythonprint(), len(), type(), int()
User-definedCreated by the programmerdef add(a, b):
RecursiveCalls itselfdef fact(n):

Function Syntax:

def function_name(parameters):
    """Docstring (optional)"""
    # Function body
    return value  # Optional

Function Components:

  • def keyword — starts the function definition
  • Function name — follows Python naming rules
  • Parameters — optional, input values in parentheses
  • Function body — indented block of code
  • return — optional, sends a value back to the caller

Examples:

# 1. Function without parameters and without return
def greet():
    print("Hello, Welcome!")

greet()  # Call the function

# 2. Function with parameters and without return
def display(name, age):
    print("Name:", name)
    print("Age:", age)

display("Ravi", 16)

# 3. Function with parameters and return value
def add(a, b):
    return a + b

result = add(10, 20)
print("Sum =", result)  # Output: Sum = 30

# 4. Function with default parameter
def power(base, exp=2):
    return base ** exp

print(power(5))     # 25 (uses default exp=2)
print(power(5, 3))  # 125 (uses provided exp=3)

Program: Factorial using function

# Program to find factorial using a function
def factorial(n):
    """Calculate factorial of a non-negative integer."""
    if n < 0:
        return "Factorial not defined for negative numbers"
    fact = 1
    for i in range(1, n + 1):
        fact = fact * i
    return fact

# Main program
num = int(input("Enter a number: "))
result = factorial(num)
print("Factorial of", num, "=", result)

Output:

Enter a number: 5 Factorial of 5 = 120

Q2. Explain recursion with examples. Write a recursive function to find the Fibonacci series.
Answer

Recursion: Recursion is a technique where a function calls itself to solve a problem by breaking it into smaller sub-problems.

Key Components of a Recursive Function: 1. Base Case: The condition that stops the recursion. Without it, the function calls itself infinitely. 2. Recursive Case: The part where the function calls itself with a smaller input, moving toward the base case.

How Recursion Works:

# Simple recursive function: Calculate power
def power(base, exp):
    if exp == 0:           # Base case
        return 1
    else:                  # Recursive case
        return base * power(base, exp - 1)

print(power(2, 3))  # Output: 8
# Trace: 2 * power(2,2) → 2 * 2 * power(2,1) → 2 * 2 * 2 * power(2,0) → 2 * 2 * 2 * 1 = 8

Example: Recursive factorial

def factorial(n):
    if n == 0 or n == 1:    # Base case
        return 1
    else:                    # Recursive case
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120
# Trace: 5 * f(4) → 5 * 4 * f(3) → 5 * 4 * 3 * f(2) → 5 * 4 * 3 * 2 * f(1) → 5 * 4 * 3 * 2 * 1 = 120

Example: Recursive Fibonacci

The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... Each number is the sum of the two preceding numbers.

# Program to print Fibonacci series using recursion
def fibonacci(n):
    """Return the nth Fibonacci number."""
    if n <= 0:           # Base case 1
        return 0
    elif n == 1:         # Base case 2
        return 1
    else:                # Recursive case
        return fibonacci(n - 1) + fibonacci(n - 2)

# Print first N Fibonacci numbers
N = int(input("Enter number of terms: "))
print("Fibonacci series:")
for i in range(N):
    print(fibonacci(i), end=" ")

Output:

Enter number of terms: 10 Fibonacci series: 0 1 1 2 3 5 8 13 21 34

Advantages of Recursion:

  • Simplifies complex problems (e.g., tree traversal, factorial)
  • Code is shorter and more elegant
  • Naturally fits problems defined recursively

Disadvantages of Recursion:

  • Uses more memory (call stack)
  • Slower than iterative solutions for large inputs
  • Risk of stack overflow if base case is missing

Q3. Explain Python modules with examples. Write a program using the math and random modules.
Answer

What is a Module? A module is a Python file (.py) containing functions, classes, and variables. Modules help organise code into reusable components.

Importing Modules:

MethodSyntaxAccess
Import entire moduleimport mathmath.sqrt(16)
Import specific functionfrom math import sqrtsqrt(16)
Import everythingfrom math import *sqrt(16)
Import with aliasimport math as mm.sqrt(16)

Built-in Modules:

ModulePurposeKey Functions
mathMathematical operationssqrt(), ceil(), floor(), pow(), pi, e
randomRandom number generationrandint(), random(), choice(), shuffle()
sysSystem-specific parametersargv, version, exit()
osOperating system interfacesgetcwd(), listdir(), path.join()
statisticsStatistical operationsmean(), median(), mode()

math module examples:

import math

print(math.sqrt(25))      # 5.0 — Square root
print(math.ceil(4.2))     # 5   — Round up
print(math.floor(4.8))    # 4   — Round down
print(math.pow(2, 3))     # 8.0 — 2 raised to 3
print(math.fabs(-7))      # 7.0 — Absolute value (float)
print(math.gcd(12, 18))   # 6   — Greatest common divisor
print(math.pi)            # 3.141592653589793
print(math.e)             # 2.718281828459045
print(math.factorial(5))  # 120 — Factorial

random module examples:

import random

print(random.randint(1, 10))    # Random integer from 1 to 10 (inclusive)
print(random.random())           # Random float between 0.0 and 1.0
print(random.uniform(1, 10))     # Random float between 1 and 10
print(random.choice(["a", "b", "c"]))  # Random item from list

Program: Using math and random modules together

import math
import random

# Program: Random circle area and statistics
print("=== Circle Area Calculator ===")
r = float(input("Enter radius of circle: "))
area = math.pi * math.pow(r, 2)
circumference = 2 * math.pi * r
print(f"Area of circle = {area:.2f}")
print(f"Circumference = {circumference:.2f}")

print("\n=== Random Number Game ===")
target = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100!")
guess = int(input("Guess the number: "))

if guess == target:
    print("Congratulations! You guessed it right!")
else:
    print("Wrong! The number was", target)
    print("Your guess was off by", math.fabs(guess - target))

Output:

=== Circle Area Calculator === Enter radius of circle: 5 Area of circle = 78.54 Circumference = 31.42 === Random Number Game === I'm thinking of a number between 1 and 100! Guess the number: 42 Wrong! The number was 73 Your guess was off by 31.0

Creating a user-defined module:

# Save this as mymodule.py
def add(a, b):
    return a + b

def greet(name):
    return "Hello, " + name + "!"

PI = 3.14159
# In another Python file
import mymodule

print(mymodule.add(5, 3))     # 8
print(mymodule.greet("Ravi")) # Hello, Ravi!
print(mymodule.PI)             # 3.14159

Common Mistakes to Avoid

1. Forgetting the colon after def — The function definition must end with a colon: def add(a, b):

2. Not indenting the function body — All code inside a function must be indented (4 spaces).

3. Confusing parameters and arguments — Parameters are placeholders in the definition; arguments are actual values in the call.

4. Forgetting to call the function — Defining a function does not execute it. You must call it: greet("Ravi")

5. Missing base case in recursion — Every recursive function must have a base case. Without it, you get infinite recursion and a RecursionError.

6. Using print() instead of return — print() displays a value but does not send it back. Use return to send a result to the caller.

7. Modifying global variables without global keyword — To modify a global variable inside a function, declare it with global varname. Otherwise, Python creates a local variable.

8. Default parameters before non-default — def f(a=5, b) is invalid. Default parameters must come after all non-default parameters: def f(b, a=5).


Exam Checklist

Before your exam, make sure you can:

  • [ ] Define and call functions with and without parameters
  • [ ] Differentiate between parameters and arguments
  • [ ] Use return to send values back from functions
  • [ ] Explain local vs global variable scope
  • [ ] Write functions with default parameters
  • [ ] Explain recursion and identify base case and recursive case
  • [ ] Write recursive functions (factorial, Fibonacci)
  • [ ] Import modules using import and from...import
  • [ ] Use math module functions (sqrt, ceil, floor, pow, pi)
  • [ ] Use random module functions (randint, random, choice)
  • [ ] Create and use a user-defined module
  • [ ] Trace recursive function calls manually
  • [ ] Write programs combining functions and modules

Frequently Asked Questions

A function is a named block of reusable code that performs a specific task. It is defined using the def keyword, can accept parameters, and may return a value using the return statement.