Current Affairs updated daily
KalviGavaniKalviGavani

Python Functions Exercise Solutions | KalviGavani

Complete Samacheer Kalvi Class 12 Computer Science Chapter 1 exercise solutions covering Python built-in functions, user-defined functions, function arguments (positional, keyword, default, variable-length), return statement, recursion, and lambda functions with detailed code examples.

Updated 13 June 202620 min read

Exercise Solutions Available

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

View Solutions →

Chapter 1 — Function: Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise question on your own first — use your Samacheer Kalvi textbook and class notes. 2. Compare your answers with the solutions below only after you have written your own. 3. Read the explanations for MCQs and True/False items — understanding why an answer is correct is more important than the answer itself. 4. Practise the short and detailed answers by writing them in your own words; do not memorise verbatim. 5. Use the Exam Checklist at the end for a quick pre-exam revision round.


Key Concepts (Quick Recap)

  • A function is a named, reusable block of code that performs a specific task; it promotes modularity and reduces duplication.
  • Built-in functions come pre-defined in Python (e.g., len(), type(), input(), max(), min()).
  • User-defined functions are created by the programmer using the def keyword.
  • Function definition syntax: def function_name(parameters): followed by an indented body.
  • Positional arguments are matched to parameters by their order; keyword arguments are matched by name.
  • Default arguments take a default value if no argument is supplied: def greet(name="Guest"):.
  • Variable-length arguments: args collects extra positional arguments as a tuple; *kwargs collects extra keyword arguments as a dictionary.
  • The return statement sends a value back to the caller; a function without return returns None.
  • Recursion is a function calling itself; every recursive function must have a base case to stop infinite calls.
  • Lambda functions are anonymous, single-expression functions defined with the lambda keyword: lambda x: x * 2.
  • Scope of a variable determines where it is accessible — local (inside a function) or global (outside all functions).
  • Functions can call other functions; they can also be passed as arguments to other functions (higher-order functions).

I. Choose the Best Answer (MCQs)

1. Which keyword is used to define a user-defined function in Python? (a) function (b) def (c) func (d) define

Answer(b) def Python uses the def keyword to define a function. The syntax is def function_name(parameters):. Options (a), (c), and (d) are not valid Python keywords.

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

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

Answer(b) Hello, World When greet() is called without any argument, the default parameter name="World" is used. The function concatenates "Hello, " with "World".

3. Which of the following is a built-in function in Python? (a) printf() (b) scanf() (c) len() (d) main()

Answer(c) len() len() is a Python built-in function that returns the length of an object. printf() and scanf() are C functions; main() is not a built-in Python function.

4. What does a function return if it has no return statement? (a) 0 (b) "" (c) None (d) Error

Answer(c) None In Python, if a function does not contain a return statement, or the return has no value, the function automatically returns None.

5. What is the output of the following code?
def add(*args):
    return sum(args)
print(add(1, 2, 3, 4))
Answer

(a) 10 (b) (1, 2, 3, 4) (c) Error (d) [1, 2, 3, 4]

Answer(a) 10 *args collects the positional arguments (1, 2, 3, 4) into a tuple. sum(args) adds them up to 10.

6. Which of the following defines a lambda function to calculate the square of a number? (a) lambda x: x x (b) def lambda x: x x (c) lambda(x): x x (d) square = lambda x {return x x}

*Answer: (a) lambda x: x x** A lambda function is defined with the lambda keyword, followed by parameters, a colon, and a single expression. No def, no parentheses around parameters, and no return keyword are needed.


7. What will be the output of the following?
def test(a, b=5, c=10):
    return a + b + c
print(test(3, c=20))
Answer

(a) 33 (b) 28 (c) 13 (d) Error

Answer(b) 28 a gets 3 (positional), b keeps its default 5 (not overridden), c gets 20 (keyword argument). So 3 + 5 + 20 = 28.

8. Recursion must have which of the following to prevent infinite calls? (a) Loop counter (b) Base case (c) Global variable (d) Break statement

Answer(b) Base case A recursive function must have a base case (also called the termination condition) that stops the recursion. Without it, the function calls itself infinitely, causing a RecursionError.

9. Which of the following collects keyword arguments into a dictionary? (a) args (b) kwargs (c) kwargs (d) **args

Answer(b) kwargs kwargs collects any extra keyword arguments into a dictionary where keys are argument names and values are argument values. *args collects positional arguments into a tuple.

10. What is the output of the following?
def func(a, b):
    return a * b
result = func(b=4, a=5)
print(result)
Answer

(a) 9 (b) 20 (c) Error (d) 54

Answer(b) 20 When using keyword arguments, the order does not matter. a=5 and b=4 are matched by name, so 5 * 4 = 20.

II. Fill in the Blanks

1. The keyword used to define a function in Python is def.

2. A function that calls itself is called a recursive function.

3. The lambda keyword is used to create anonymous functions in Python.

4. The built-in function len() returns the number of items in an object.

5. In a function definition, *args collects positional arguments into a tuple.

6. In a function definition, kwargs collects keyword arguments into a dictionary**.

7. If a function does not have a return statement, it returns None.

8. Arguments that are passed by matching parameter names are called keyword arguments.

9. The process of a function calling itself is known as recursion.

10. Default arguments must be placed after non-default arguments in the function definition.


III. True or False

1. A lambda function can contain multiple expressions. False. A lambda function can contain only a single expression. It cannot have multiple statements or a block of code.

2. Built-in functions are predefined functions available in Python. True. Built-in functions like len(), print(), type(), and input() are already defined in Python and can be used without importing any module.

3. A function can return more than one value in Python. True. A Python function can return multiple values as a tuple, e.g., return a, b. The caller can unpack them: x, y = func().

4. *args and kwargs can be used together in a function definition. True. The order must be: positional, args, keyword/default, kwargs. Example: def func(a, args, b=5, **kwargs).

5. The return statement can be used outside a function. False. The return statement can only be used inside a function. Using it outside causes a SyntaxError.

6. Positional arguments must appear before keyword arguments in a function call. True. In a function call, all positional arguments must come before any keyword arguments. Otherwise, Python raises a SyntaxError.

7. A recursive function without a base case runs indefinitely. False. Python has a recursion limit (default 1000). Without a base case, the function will eventually raise a RecursionError: maximum recursion depth exceeded.

8. The global keyword is used to read a global variable inside a function. False. You can read a global variable inside a function without the global keyword. The global keyword is needed only when you want to modify (assign to) a global variable inside a function.

9. Default argument values are evaluated once at function definition time. True. Default argument values are set when the function is defined, not each time it is called. This matters for mutable defaults like lists — they persist across calls.

10. A function can be passed as an argument to another function in Python. True. Functions are first-class objects in Python. They can be passed as arguments, returned from other functions, and assigned to variables.


IV. Match the Following

Set A

AB
1. defc. Keyword to define a function
2. returne. Sends a value back to the caller
3. *argsa. Collects positional arguments into a tuple
4. lambdad. Creates an anonymous function
5. Noneb. Default return value of a function

Set B

AB
1. len()d. Built-in function returning the length
2. Recursione. Function calling itself
3. Keyword argumenta. Argument passed using parameter name
4. Default argumentc. Argument with a pre-set value
5. **kwargsb. Collects keyword arguments into a dictionary

V. Short Answer Questions

1. What is a function? What are its advantages?
Answer

A function is a named, self-contained block of code that performs a specific task. It may accept inputs (parameters) and produce outputs (return values).

Advantages:

  • Reusability: Write once, call many times — avoids code duplication.
  • Modularity: Large programs are broken into smaller, manageable units.
  • Readability: Well-named functions make code easier to understand.
  • Debugging: Errors can be isolated to specific functions, making debugging easier.
  • Maintainability: Changes to a function affect all calls, simplifying updates.

2. Differentiate between built-in functions and user-defined functions.
Answer
FeatureBuilt-in FunctionsUser-defined Functions
DefinitionPre-defined in PythonCreated by the programmer
AvailabilityAvailable without importMust be defined before use
Exampleslen(), type(), print(), input()def add(a, b): return a + b
CustomisationCannot be modifiedFully customisable
PurposeCommon, general-purpose tasksSpecific, task-oriented operations

3. Explain the different types of function arguments in Python with examples.
Answer

Python supports four types of function arguments:

(i) Positional arguments — matched by order:

def add(a, b):
    return a + b
print(add(3, 5))  # a=3, b=5 → 8

(ii) Keyword arguments — matched by name:

def greet(name, msg):
    return msg + ", " + name
print(greet(msg="Hello", name="Kavi"))  # Hello, Kavi

(iii) Default arguments — have a pre-set value:

def power(base, exp=2):
    return base ** exp
print(power(5))    # 25 (exp defaults to 2)
print(power(5, 3)) # 125 (exp = 3)

(iv) Variable-length arguments:

  • *args collects extra positional arguments as a tuple.
  • **kwargs collects extra keyword arguments as a dictionary.
def show(*args, **kwargs):
    print(args)    # (1, 2, 3)
    print(kwargs)  # {'a': 10, 'b': 20}
show(1, 2, 3, a=10, b=20)

4. What is recursion? Write a recursive function to find the factorial of a number.
Answer

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem. Every recursive function must have:

  • A base case: the condition that stops recursion.
  • A recursive case: the function calls itself with a smaller input.
def factorial(n):
    if n == 0 or n == 1:   # Base case
        return 1
    else:                    # Recursive case
        return n * factorial(n - 1)

print(factorial(5))  # 5 * 4 * 3 * 2 * 1 = 120

Trace for factorial(5):

factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 * factorial(1) = 5 * 4 * 3 * 2 * 1 = 120

5. What is a lambda function? Give examples.
Answer

A lambda function is an anonymous (nameless), single-expression function defined using the lambda keyword. It has the syntax:

lambda arguments: expression

Examples:

# Square of a number
square = lambda x: x * x
print(square(5))  # 25

# Add two numbers
add = lambda a, b: a + b
print(add(3, 7))  # 10

# Lambda with default argument
greet = lambda name="World": "Hello, " + name
print(greet())      # Hello, World
print(greet("Kavi"))  # Hello, Kavi

# Lambda used with sorted()
students = [("Kavi", 85), ("Arun", 92), ("Bala", 78)]
ranked = sorted(students, key=lambda x: x[1], reverse=True)
print(ranked)  # [('Arun', 92), ('Kavi', 85), ('Bala', 78)]

6. Differentiate between return and print in a function.
Answer
Featurereturnprint
PurposeSends a value back to the callerDisplays output on the screen
UsabilityReturned value can be stored/used in expressionsOutput cannot be captured or reused
DefaultWithout return, function returns Noneprint itself returns None
Exampledef add(a,b): return a+b; x=add(1,2) → x=3def add(a,b): print(a+b); x=add(1,2) → x=None
def with_return(a, b):
    return a + b

def with_print(a, b):
    print(a + b)

result = with_return(3, 4)  # result = 7
result2 = with_print(3, 4)   # prints 7, but result2 = None

VI. Detailed Answer Questions

1. Explain user-defined functions in Python with syntax, examples, and types.
Answer

A user-defined function is created by the programmer to perform a specific task.

Syntax:

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

Components:

  • def — keyword that starts the function definition.
  • function_name — identifier following Python naming rules.
  • parameters — optional input variables listed in parentheses.
  • Docstring — optional description of the function (triple-quoted).
  • return — optional statement to send a value back.

Types of user-defined functions:

TypeDescriptionExample
No parameter, no returnDoes a task, no input/outputdef greet(): print("Hello")
With parameter, no returnTakes input, processes itdef show(n): print(n*n)
No parameter, with returnNo input, returns outputdef pi(): return 3.14
With parameter, with returnTakes input, returns outputdef add(a,b): return a+b

Examples:

# 1. No parameter, no return
def greet():
    print("Welcome to Python!")

greet()  # Output: Welcome to Python!

# 2. With parameter, no return
def display_square(n):
    print(f"Square of {n} is {n*n}")

display_square(5)  # Output: Square of 5 is 25

# 3. No parameter, with return
def get_pi():
    return 3.14159

print(get_pi())  # Output: 3.14159

# 4. With parameter, with return
def multiply(a, b):
    return a * b

result = multiply(4, 6)
print(result)  # Output: 24

2. Explain function arguments in Python with examples for each type.
Answer

Python functions can receive data through arguments. There are four types:

(i) Positional Arguments Arguments are matched to parameters by their position (order).

def subtract(a, b):
    return a - b

print(subtract(10, 3))  # a=10, b=3 → 7
# Order matters: subtract(3, 10) gives -7

(ii) Keyword Arguments Arguments are passed by explicitly naming the parameter. Order does not matter.

def greet(name, msg):
    print(msg + ", " + name + "!")

greet(name="Kavi", msg="Good morning")  # Good morning, Kavi!
greet(msg="Hello", name="Bala")         # Hello, Bala!

(iii) Default Arguments Parameters are given default values. If no argument is passed, the default is used.

def power(base, exp=2):
    return base ** exp

print(power(5))     # 25  (exp defaults to 2)
print(power(5, 3))  # 125 (exp is 3)

Important rule: Non-default arguments must come before default arguments.

# Correct:
def func(a, b=10, c=20): pass

# Wrong — causes SyntaxError:
# def func(a=10, b, c): pass

(iv) Variable-length Arguments args collects extra positional arguments into a tuple; *kwargs collects extra keyword arguments into a dictionary.

def total(*args):
    print(args)       # (10, 20, 30)
    print(sum(args))  # 60

total(10, 20, 30)

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} = {value}")

display_info(name="Kavi", age=17, grade="A")
# name = Kavi
# age = 17
# grade = A

Combined example:

def mixed(a, b, *args, c=10, **kwargs):
    print(f"a={a}, b={b}")       # a=1, b=2
    print(f"args={args}")         # args=(3, 4, 5)
    print(f"c={c}")               # c=10
    print(f"kwargs={kwargs}")     # kwargs={'x': 100, 'y': 200}

mixed(1, 2, 3, 4, 5, x=100, y=200)

3. Explain recursion in detail with an example. What are its advantages and disadvantages?
Answer

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

Essential components: 1. Base case: The condition that stops the recursion. 2. Recursive case: The function calls itself with a modified (smaller) argument.

Example — Fibonacci series:

def fibonacci(n):
    if n <= 0:
        return 0          # Base case 1
    elif n == 1:
        return 1          # Base case 2
    else:
        return fibonacci(n-1) + fibonacci(n-2)  # Recursive case

for i in range(10):
    print(fibonacci(i), end=" ")
# Output: 0 1 1 2 3 5 8 13 21 34

Example — Sum of digits:

def sum_digits(n):
    if n == 0:
        return 0                    # Base case
    else:
        return (n % 10) + sum_digits(n // 10)  # Recursive case

print(sum_digits(1234))  # 1+2+3+4 = 10

Advantages:

  • Code is simpler and more elegant for problems that have a natural recursive structure (e.g., tree traversal, factorial, Fibonacci).
  • Complex problems like Tower of Hanoi and DFS can be expressed concisely.
  • Reduces the need for complex loop structures.

Disadvantages:

  • Recursive calls consume stack memory; deep recursion can cause RecursionError.
  • Generally slower than iterative solutions due to function call overhead.
  • Can be harder to debug because of multiple nested calls.
  • Each call adds overhead (saving state, returning).

Comparison table:

FeatureRecursionIteration
DefinitionFunction calls itselfUses loops (for/while)
MemoryHigher (call stack)Lower (single frame)
SpeedSlower (call overhead)Faster
Code lengthShorter, elegantLonger, explicit
Base conditionRequiredLoop condition

4. Explain lambda functions with syntax, characteristics, and examples.
Answer

A lambda function is an anonymous, single-expression function defined using the lambda keyword.

Syntax:

lambda arguments: expression

Characteristics:

  • Anonymous — no function name (though it can be assigned to a variable).
  • Single expression only — cannot contain multiple statements or a block.
  • No explicit return — the expression's result is automatically returned.
  • Can take any number of arguments but only one expression.

Examples:

# Basic lambda
square = lambda x: x * x
print(square(6))  # 36

# Lambda with multiple arguments
add = lambda a, b, c: a + b + c
print(add(1, 2, 3))  # 6

# Lambda with default argument
greet = lambda name="World": "Hello, " + name
print(greet())        # Hello, World
print(greet("Kavi"))  # Hello, Kavi

# Immediately invoked lambda (IIFE)
result = (lambda x, y: x * y)(4, 5)
print(result)  # 20

# Lambda used with filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# Lambda used with map()
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Lambda used with sorted()
students = [("Kavi", 85), ("Arun", 92), ("Bala", 78)]
ranked = sorted(students, key=lambda s: s[1], reverse=True)
print(ranked)  # [('Arun', 92), ('Kavi', 85), ('Bala', 78)]

# Conditional expression in lambda
max_of_two = lambda a, b: a if a > b else b
print(max_of_two(15, 9))  # 15

Lambda vs def:

Featurelambdadef
NameAnonymous (can be assigned)Named
BodySingle expressionMultiple statements
ReturnImplicit (expression result)Explicit return needed
StatementsNo if-else blocks, loopsFull Python statements
Use caseShort, one-line operationsComplex, multi-step logic

5. Explain the scope of variables in Python with examples. Illustrate local, global, and the global keyword.
Answer

Scope refers to the region of a program where a variable is accessible.

(i) Local Scope A variable defined inside a function is local to that function. It cannot be accessed outside.

def my_func():
    x = 10    # Local variable
    print(x)  # 10

my_func()
# print(x)  # NameError: name 'x' is not defined

(ii) Global Scope A variable defined outside all functions is global and can be accessed anywhere.

x = 50   # Global variable

def my_func():
    print(x)  # 50 (reading global x)

my_func()
print(x)  # 50

(iii) The global Keyword To modify a global variable inside a function, use the global keyword. Without it, assignment inside a function creates a new local variable.

count = 0   # Global

def increment():
    global count       # Declare count as global
    count = count + 1  # Modifies global count

increment()
increment()
print(count)  # 2

Without global — creates a local variable (shadowing):

x = 10

def modify():
    x = 20    # Creates a new local x, does NOT modify global x
    print("Inside:", x)  # 20

modify()
print("Outside:", x)  # 10 (global x unchanged)

With global — modifies the global variable:

x = 10

def modify():
    global x   # Refers to the global x
    x = 20     # Modifies global x
    print("Inside:", x)  # 20

modify()
print("Outside:", x)  # 20

Key rules:

  • Reading a global variable inside a function does not require global.
  • Modifying (assigning to) a global variable inside a function does require global.
  • Local variables are destroyed when the function exits.
  • Avoid excessive use of global — prefer passing parameters and returning values.

Common Mistakes

1. Forgetting the return statement: A function that computes a value but does not return it will give None. Always use return when the caller needs the result.

2. Confusing positional and keyword argument order: In a function call, all positional arguments must come before keyword arguments. func(5, b=3) is correct; func(b=3, 5) causes a SyntaxError.

3. Placing default arguments before non-default arguments: def func(a=5, b): is invalid. Default arguments must follow non-default ones: def func(a, b=5):.

4. Missing the base case in recursion: A recursive function without a base case will call itself infinitely until Python raises RecursionError. Always define when the recursion should stop.

5. Using mutable objects as default arguments: def func(items=[]): shares the same list across all calls. Use def func(items=None): items = items or [] instead.

6. Modifying a global variable without global: Assigning to a variable with the same name as a global inside a function creates a new local variable, leaving the global unchanged.

7. Using lambda for multi-line logic: Lambda functions can only contain a single expression. For complex logic with multiple statements, use def instead.


Exam Checklist

  • [ ] Can define a user-defined function with correct syntax (def, parameters, return)
  • [ ] Can identify and use built-in functions (len(), type(), input(), etc.)
  • [ ] Can distinguish between positional, keyword, default, and variable-length arguments
  • [ ] Know the order rule: positional → args → default → *kwargs
  • [ ] Can write a recursive function with a proper base case
  • [ ] Can trace recursive function calls step by step
  • [ ] Can define and use lambda functions, including with map(), filter(), sorted()
  • [ ] Understand the difference between return and print
  • [ ] Can explain local vs global scope and the global keyword
  • [ ] Know that a function without return returns None

Frequently Asked Questions

A function is a named, reusable block of code that performs a specific task. It may accept parameters (inputs) and may return a value. Functions promote modularity, reduce code duplication, and improve readability.