0% found this document useful (0 votes)
3 views31 pages

Functions in Python Notes

This document provides a comprehensive overview of functions in Python for Class 12 Computer Science students, covering definitions, types, and benefits of functions, as well as detailed explanations of function components such as headers, parameters, and return statements. It also discusses different argument types including positional, default, keyword, and variable-length arguments, along with examples and common pitfalls. Additionally, the document includes exam tips and practice questions relevant to the CBSE curriculum.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views31 pages

Functions in Python Notes

This document provides a comprehensive overview of functions in Python for Class 12 Computer Science students, covering definitions, types, and benefits of functions, as well as detailed explanations of function components such as headers, parameters, and return statements. It also discusses different argument types including positional, default, keyword, and variable-length arguments, along with examples and common pitfalls. Additionally, the document includes exam tips and practice questions relevant to the CBSE curriculum.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Functions in Python Class 12 – Computer Science (083)

FUNCTIONS IN PYTHON
Complete Study Notes • Class 12 – CBSE Computer Science (083)

In this chapter you will learn:


• What a function is and why programmers use them
• Built-in, module, and user-defined functions
• The anatomy of a function definition — header, parameters, body, return
• Positional, default, keyword, and variable-length arguments
• Returning single and multiple values from a function
• Local vs. global scope, and the global keyword
• Common exam pitfalls + CBSE board-style practice questions with answers

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 1 of 31
Functions in Python Class 12 – Computer Science (083)

1. What Is a Function?
A function is a named, reusable block of organized code that performs a single, well-defined task. Instead of
writing the same logic again and again, you write it once inside a function and simply call (invoke) that function
whenever you need it.
A function executes only when it is called — defining it does not run it. Python gives you many ready-made
built-in functions such as print(), len(), and type(), and it also lets you write your own functions, called User-
Defined Functions (UDFs).
When a function is called, data can be handed to it through function parameters. After it finishes executing,
the function may optionally send data back to the caller using a return statement.

Quick Definition
Function = a self-contained block of code, identified by a name, that performs a specific task and can
optionally accept inputs (parameters) and send back an output (return value).

A Simple First Example


Here is the smallest possible function — one that just greets the user:

def greet():
print("Hello, welcome to Python functions!")

greet() # function call


greet() # called again — reusability in action!

Output:
Hello, welcome to Python functions!
Hello, welcome to Python functions!

Notice that the line greet() had to appear for anything to happen. Simply writing the def block does not display
anything — the function had to be called twice for the message to print twice. This is the essence of
reusability.

💡 Exam Tip
A very common 1-mark CBSE question asks you to identify which line in a piece of code is the ‘function
call’ versus the ‘function definition’. Remember: the definition starts with def; the call simply uses the
function name followed by parentheses, with no def keyword.

2. Benefits of Using Functions


Functions are one of the most powerful tools for writing clean, maintainable programs. CBSE frequently asks
you to state and justify these advantages, so understand each with an example, not just a one-line definition.

2.1 Code Reusability

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 2 of 31
Functions in Python Class 12 – Computer Science (083)

A function, once created, can be called as many times as required — from anywhere in the program — without
rewriting the logic.

def square(n):
return n*n

print(square(4)) # reused for 4


print(square(9)) # reused for 9 — no need to rewrite n*n again

Output:
16
81

2.2 Modularity
Functions let you break a large program into smaller, independent blocks (modules), where each block handles
one specific task — making the program easier to design, test, and debug.

def takeInput():
... # handles only input
def processData():
... # handles only processing
def showResult():
... # handles only output

2.3 Understandability (Readability)


Well-named functions make a program self-documenting. Reading calculateInterest() tells you exactly what
that block does, without studying its internal code line by line.

2.4 Procedural Abstraction


Once a function has been written and tested, a programmer using it only needs to know what it does and how
to call it — not how it is implemented internally. This ‘hiding’ of internal detail is called procedural abstraction.

Real-World Analogy
When you use a calculator’s square-root button, you don’t need to know the internal algorithm it uses.
You only need to know: press the button, get the square root. That is exactly procedural abstraction —
you use the function's interface, not its internal implementation.

2.5 Easier Debugging & Reduced Program Length


Since each task lives inside its own function, an error is easier to isolate — you know exactly which function to
inspect. Additionally, avoiding repeated code keeps the overall program shorter.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 3 of 31
Functions in Python Class 12 – Computer Science (083)

3. Types of Functions in Python


Python organizes functions into three categories, based on who wrote them and where they live.

3.1 Built-in Functions


Ready-to-use functions that are already defined inside Python itself. A programmer can use them directly,
anytime, without any extra setup.

print(len("COMPUTER")) # len() is built-in


print(type(25)) # type() is built-in
print(max(4, 9, 2)) # max() is built-in

Output:
8
<class 'int'>
9

3.2 Functions Defined in Modules


Some functions are bundled inside separate files called modules (e.g. math, random, statistics). To use them,
the programmer must first import the module, after which its functions become available using dot notation.

import math
p = [Link](5, 2) # 5 raised to the power 2
print(p)
print([Link](81)) # another function from the same module

Output:
25.0
9.0

3.3 User-Defined Functions (UDFs)


Functions that the programmer defines to perform a specific task are called User-Defined Functions. The
keyword def is used to define a new function in Python.

def isEven(n):
if n % 2 == 0:
return True
else:
return False

print(isEven(10))
print(isEven(7))

Output:
True

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 4 of 31
Functions in Python Class 12 – Computer Science (083)

False

Compare All Three


Built-in → already available, no import needed (print, len). Module-based → needs an import statement
first ([Link]). User-defined → written by you using def, to solve your own specific problem.

4. Elements of a Function Definition


Every user-defined function is built from five distinct parts. Examiners often give you a function and ask you to
label or explain each part, so learn to spot all five on sight.

def sum(a, b): # ← FUNCTION HEADER


total = a + b # ← FUNCTION BODY begins (indented)
return total # ← RETURN STATEMENT

4.1 Function Header


The first line of the function definition. It starts with the keyword def, followed by the function name and a
parenthesized list of parameters, and ends with a colon ( : ).

def sum(a, b): #function Header

4.2 Parameters
The variable names listed inside the parentheses ( ) of the function header. They act as placeholders for the
values that will be supplied when the function is called.

4.3 Function Body


The set of indented statements beneath the function header. These statements carry out the actual task the
function is designed for.

4.4 Indentation
Every statement inside the function body must start with the same amount of blank space (commonly 4
spaces, by convention). Python uses indentation — not braces { } — to mark which statements belong inside
the function.

⚠️ Common Mistake
Inconsistent indentation (mixing tabs and spaces, or using different numbers of spaces within the same
block) raises an IndentationError. This is one of the most frequent ‘spot the error’ questions in board
papers.

4.5 Return Statement


A function may include a return statement to send a value back to the caller. A return statement can also be
used alone, without any value or expression — in that case the function simply ends and sends back None.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 5 of 31
Functions in Python Class 12 – Computer Science (083)

def checkAge(age):
if age < 18:
return # returns nothing meaningful (None)
return "Eligible to vote"

print(checkAge(15))
print(checkAge(20))

Output:
None
Eligible to vote

Flow of Execution in a Function Call


When a program runs and reaches a function call, control jumps from that line to the function's definition. The
function body executes line by line. As soon as a return statement is encountered (or the last line of the
function finishes), control jumps back to exactly the point right after the call — and execution resumes from
there.

def myFun(x, y): # ① control jumps here when called


z = x + y
return z # ② control jumps back to the caller

a = 10
b = 20
result = myFun(a, b) # ① function call — control leaves this line
print(result) # ② execution resumes here after return

Output:
30

Step-by-Step Trace
1) a=10, b=20 are set. 2) myFun(a, b) is called — program control shifts to the function definition; x
receives 10, y receives 20. 3) Inside the function, z = x + y = 30. 4) return z sends 30 back and control
returns to the line right after the call. 5) result now holds 30, which print(result) displays.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 6 of 31
Functions in Python Class 12 – Computer Science (083)

5. Arguments and Parameters in Functions


In Python, the variables listed inside the parentheses of a function definition are called parameters (also formal
parameters / formal arguments). The values listed inside the parentheses of a function call are called
arguments (also actual parameters / actual arguments).

Parameter vs. Argument — Don't Mix These Up!


PARAMETER lives in the function definition (def line). ARGUMENT lives in the function call. Example: def
add(x, y): → x and y are parameters. add(5, 3) → 5 and 3 are arguments.

Python supports four types of arguments / formal parameters:


1. Positional Argument
2. Default Argument
3. Keyword Argument
4. Variable-Length Argument

5.1 Positional Arguments


When the arguments in a function call match the number and order of parameters defined in the function
header, they are called positional arguments. Each argument is matched to the parameter occupying the same
position.

def myfun(x, y, z):


print(x, y, z)

myfun(a, b, c) # 3 values (all variables) passed as arguments


myfun(a, 8, 9) # 3 values (1 variable + 2 literals) passed
myfun(a, b) # Error: missing 1 required positional argument: 'z'

⚠️ Important Rule
Positional arguments are mandatory — you cannot skip a value or change the order of the arguments
being passed unless you switch to keyword arguments.

A second, fully worked example:

def employeeInfo(name, age, salary):


print(name, "is", age, "years old, earns Rs.", salary)

employeeInfo("Riya", 24, 45000)

Output:
Riya is 24 years old, earns Rs. 45000

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 7 of 31
Functions in Python Class 12 – Computer Science (083)

5.2 Default Arguments


Default values can be assigned to parameters in the function header itself, while defining the function. These
default values are used only when the function call does not supply a matching argument for that parameter.

def findresult(mark_secured, passing_mark=30):


if mark_secured >= passing_mark:
print("pass")
else:
print("fail")

findresult(46, 40) # default NOT used — call has matching arguments


findresult(52) # default IS used — passing_mark becomes 30

Output:
pass
pass

In the first call, findresult(46, 40), both arguments are supplied, so 40 overrides the default. In the second call,
findresult(52), only one value is given, so passing_mark falls back to its default value of 30.

⚠️ Golden Rule (Frequently Tested!)


Non-default (positional) arguments cannot follow default arguments in a function header. def calc(a,
b=10, c): is INVALID, because the non-default parameter c appears after the default parameter b. The
correct order would be def calc(a, c, b=10):.

A second example showing the invalid ordering, exactly the kind of ‘find the error’ question CBSE asks:

def display(x=5, y): # INVALID -- default parameter x is before


print(x, y) # non-default parameter y

Corrected version: def display(y, x=5):

5.3 Keyword Arguments


Python allows a function to be called by passing arguments in any order, as long as the programmer explicitly
specifies the parameter name for each value in the function call. These are called keyword arguments.

def findpow(base, exponent):


print(base**exponent)

findpow(5, 2) # positional — base=5, exponent=2


findpow(exponent=5, base=2) # keyword — order doesn't matter here

Output:
25
32

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 8 of 31
Functions in Python Class 12 – Computer Science (083)

In the first call, base receives 5 and exponent receives 2 purely by position. In the second call, because the
names are explicitly stated, base receives 2 and exponent receives 5 — even though the order looks reversed.

Mixing Positional and Keyword Arguments


A function call can combine both styles, but positional arguments must always come before keyword
arguments.

def billDetails(item, qty, price):


print(item, qty, price)

billDetails("Pen", price=10, qty=5) # valid -- positional first, then


keyword
billDetails(qty=5, "Pen", price=10) # INVALID -- SyntaxError

5.4 Variable-Length Arguments


A variable-length argument allows a single parameter to receive any number of values from the function call.
In the function header, this parameter is written with an asterisk ( * ) before its name.

def findsum(*x):
sum = 0
for i in x:
sum = sum + i
print("sum of numbers is:", sum)

findsum(6, 2, 8, 5, 2)
findsum(34, 2, 4, 10, 22, 14, 6)

Output:
sum of numbers is: 23
sum of numbers is: 92

Inside the function, the parameter x behaves exactly like a tuple holding every value that was passed — it can
hold any number of arguments, including zero.

Why *args?
By convention, programmers commonly name the variable-length parameter *args (short for
arguments) instead of *x, though any valid identifier works. There is also **kwargs for variable-length
keyword arguments, where each argument has a name=value form — useful but beyond the typical
Class 12 CBSE scope.

5.5 Quick Comparison — All Four Argument Types

Type Rule Example Call

Order & count must match the definition


Positional f(10, 20)
exactly

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 9 of 31
Functions in Python Class 12 – Computer Science (083)

Used only when the call omits that


Default f(10) → uses default for 2nd param
argument

Keyword Name=value pairs; order doesn't matter f(y=20, x=10)

*param collects any number of values as a


Variable-Length f(1, 2, 3, 4)
tuple

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 10 of 31
Functions in Python Class 12 – Computer Science (083)

6. Returning Values from a Function


Functions in Python can send back values to the place from where they were called, using the return
statement. A function may or may not return a value, and a Python function can even return multiple values at
once.

⚠️ Important
The return statement immediately terminates function execution the moment it is encountered. Any
code written after a return statement, within the same block, is never executed.

6.1 Returning a Single Value

def sayhello(name):
message = "hello " + name
return message

m = sayhello("amit")
print(m)

Output:
hello amit

6.2 Returning Multiple Values


A single return statement can send back more than one value, separated by commas. Python automatically
packs them into a tuple, which can then be unpacked into separate variables at the call site.

def minMax(numbers):
return min(numbers), max(numbers)

smallest, largest = minMax([23, 5, 67, 12, 9])


print("Smallest:", smallest)
print("Largest:", largest)

Output:
Smallest: 5
Largest: 67

6.3 A Function with No Return Value


If a function has no return statement (or uses a bare return), Python automatically considers the result to be
None.

def showMessage():
print("Processing complete.")

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 11 of 31
Functions in Python Class 12 – Computer Science (083)

result = showMessage()
print(result)

Output:
Processing complete.
None

Notice that the function did print a message as a side effect, but because it never used return, the value
captured in result is None.

6.4 Code After return Is Never Executed

def test():
print("Before return")
return 100
print("After return") # this line never runs

print(test())

Output:
Before return
100

7. Scope of Variables
The part(s) of a program where a variable is legal and accessible is called its scope. Based on scope, variables
are categorized into two types.

7.1 Local Variable


A variable defined inside a function is called a local variable. Its scope is limited only to the function in which it
is defined, and it cannot be accessed from outside that function.

7.2 Global Variable


A variable defined outside all functions, directly in the main program body, is called a global variable. It can be
read from anywhere in the program, including inside functions.

def findsum(a, b):


c = a + b # a, b, c are LOCAL to findsum()
return c

x, y = 10, 20 # x, y are GLOBAL


m = findsum(x, y) # m is GLOBAL
print(m)

Output:

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 12 of 31
Functions in Python Class 12 – Computer Science (083)

30

Identifying Scope at a Glance


a, b and c are defined inside findsum(), so they are Local variables and don't exist outside the function. x,
y and m are defined outside any function (in the main body), so they are Global variables, visible
throughout the program.

7.3 Using a Global Variable Inside Local Scope


A function can read a global variable's value directly, without any special keyword. But if the function tries to
assign a new value to a name that also exists globally, Python creates a brand-new local variable instead of
changing the global one. To modify the actual global variable from inside a function, the global statement must
be used.

a = 10
def add(x):
a = x + 5 # creates a NEW local variable 'a'
print(x)

add(20)
print(a)

Output:
20
10

Inside the function, a local variable named a is created, so changes made to it do not affect the global a. That is
why print(a) outside the function still shows 10.
Now compare this with the global keyword in use:

a = 10
def add(x):
global a
a = x + 5 # modifies the GLOBAL variable 'a'
print(x)

add(20)
print(a)

Output:
20
25

When global a is declared inside the function, Python is told not to create a local variable a. Instead, the
function directly accesses and modifies the global a. So any change made inside the function (a = x + 5 = 25) is
reflected outside the function too.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 13 of 31
Functions in Python Class 12 – Computer Science (083)

💡 Exam Tip -- 'Predict the Output' Questions


When a board question shows the same variable name used both globally and inside a function, always
check first whether the global keyword is present inside that function. No global keyword means the
function's local variable is separate, and the global value remains unchanged outside. If the global
keyword is present, the function directly edits the global variable.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 14 of 31
Functions in Python Class 12 – Computer Science (083)

8. Quick Revision -- Summary Table


Use this table for last-minute revision before the exam. It condenses every important fact from this chapter
into one place.

Term Key Point

Function A named, reusable block of code that performs a specific task.

Built-in function Already defined in Python; ready to use (print, len, type).

Module function Defined inside a module; requires import first ([Link]).

User-defined function Created by the programmer using the def keyword.

Function Header First line; starts with def, ends with a colon.

Parameter Variable in the function definition's parentheses.

Argument Value supplied in the function call's parentheses.

Positional argument Order & count must exactly match the definition.

Default argument Has a preset value, used only if the call omits it.

Keyword argument Passed as name=value; order becomes irrelevant.

Variable-length argument Written as *param; collects values as a tuple.

return statement Sends a value back to the caller; ends execution immediately.

Local variable Defined inside a function; accessible only within it.

Global variable Defined outside all functions; accessible everywhere.

global keyword Lets a function modify a global variable instead of creating a local copy.

9. Common Errors & Exam Pitfalls


Board papers love to test these exact misconceptions through 'find and correct the error' and 'predict the
output' questions. Go through each one carefully.
• Default parameter placed before a non-default parameter: def f(a=5, b): is a SyntaxError. Default
parameters must always be written after all non-default (positional) parameters.
• Forgetting the colon ( : ) at the end of the header: def add(a, b) without a trailing colon raises a
SyntaxError.
• Inconsistent indentation in the function body: Mixing tab and space indentation, or using different
indent widths within the same block, raises an IndentationError.
• Assuming a function automatically returns its last computed value: Without an explicit return
statement, a function always gives back None, even if it performed calculations internally.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 15 of 31
Functions in Python Class 12 – Computer Science (083)

• Believing code after return still executes: Any statement written after a return inside the same block is
dead code and never runs.
• Modifying a global variable inside a function without using 'global': This creates a new local variable
instead and leaves the original global variable unchanged outside the function.
• Calling a function before it is defined: Python reads and executes code top to bottom; the def block for
a function must appear before the line that calls it.
• Mixing up positional & keyword argument order in a call: Positional arguments must always be listed
before keyword arguments in a function call -- f(a, b=2) is fine, but f(b=2, a) is a SyntaxError.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 16 of 31
Functions in Python Class 12 – Computer Science (083)

PRACTICE QUESTIONS
Based on CBSE Class 12 Computer Science (083) Board Exam Patterns

How These Questions Are Organized


The questions below mirror the actual CBSE board paper structure: Section A (1 mark each -- MCQ, Fill-
in-the-Blank, Assertion-Reasoning), Section B (2 marks each), Section C (3 marks each), and Section D (4-
5 marks each -- long answer / programming questions). Attempt every question before checking the
Answer Key at the end.

Section A -- 1 Mark Questions (MCQ / Fill-Ups / Assertion-Reasoning)


Q1. Which of the following is an invalid way of defining a function header in Python?
(a) def calc(a, b):

(b) def calc(a, b=5):

(c) def calc(a=5, b):

(d) def calc():

Q2. Identify the parameter(s) in the following function header: def findArea(length, breadth=10):
(a) length only

(b) breadth only

(c) length and breadth

(d) findArea

Q3. What will be the output of the following code?


def fun(x=10):
return x*2
print(fun())
(a) 10

(b) 20

(c) Error

(d) None

Q4. Which keyword is used to access and modify a global variable inside a function in Python?

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 17 of 31
Functions in Python Class 12 – Computer Science (083)

(a) nonlocal

(b) global

(c) public

(d) extern

Q5. A variable declared inside a function, accessible only within that function, is called a ____ variable.
(a) Global

(b) Local

(c) Static

(d) External

Q6. State True or False:


“While defining a function in Python, the positional parameters in the function header must always be written
after the default parameters.”
[Based on CBSE 2024 Board Paper]

Q7. Fill in the blank:


The variables mentioned inside the parentheses of a function call are known as ________, whereas those in
the function definition's header are known as ________.

Q8. Predict the Output:

a = 20
def convert(a):
b = 20
a = a + b
convert(10)
print(a)

[Based on CBSE 2024 Board Paper]

Assertion-Reasoning Questions
Directions (Q9-Q10): These questions consist of two statements, Assertion (A) and Reasoning (R). Mark the
correct choice as:
• (a) Both A and R are true, and R is the correct explanation of A.
• (b) Both A and R are true, but R is NOT the correct explanation of A.
Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh
Page 18 of 31
Functions in Python Class 12 – Computer Science (083)

• (c) A is True but R is False.


• (d) A is False but R is True.

Q9.
Assertion (A): If the arguments in a function call statement match the number and order of arguments as
defined in the function definition, such arguments are called positional arguments.
Reasoning (R): During a function call, the argument list must first contain the positional argument(s), followed
by the default argument(s).
[Based on CBSE 2022-23 Sample Paper]

Q10.
Assertion (A): A program having multiple user-defined functions is generally considered better designed than a
program with no functions at all.
Reasoning (R): Functions in a program help simplify code, avoid repetition, and improve readability and
reusability.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 19 of 31
Functions in Python Class 12 – Computer Science (083)

Section B -- 2 Mark Questions


Q11. Differentiate between a Local variable and a Global variable, with one suitable example of each.

Q12. Rewrite the following code after removing all syntax errors, underlining each correction made:

define calcArea(radius)
pi = 3.14
area = pi * radius * radius
print area

[Based on CBSE error-correction pattern, 2023-24]

Q13. What is meant by Procedural Abstraction? Explain with a suitable example.

Q14. Write the output of the following code:

def changeValue(num):
num = num * 2
return num

value = 15
newValue = changeValue(value)
print(value, newValue)

Q15. Identify and explain, with one example each, any two types of arguments supported by Python user-
defined functions.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 20 of 31
Functions in Python Class 12 – Computer Science (083)

Section C -- 3 Mark Questions


Q16. Find and correct the errors in the following code. Underline each correction made:

def EvenOdd()
for i in range (5):
num=int (input ("Enter a number")
if num/2==0:
print ("Even")
else:
print ("Odd")
EvenOdd()

[Based on CBSE 2023-24 Board Paper, Set 4]

Q17. Predict the output of the following Python code:

x = 2
def fun1():
x = 5
global y
y = 20
def fun2():
nonlocal x
x = 10
y = 30
fun2()
print(x, y)
fun1()
print(x, y)

[Based on CBSE-style nested function scope question]

Q18. Write a function findType(mtype) that accepts mtype as a parameter and displays a category label
based on the following rule: if mtype is 'A' display Action, if mtype is 'C' display Comedy, otherwise display
Other.
[Inspired by CBSE 2024 Board Paper -- findType(mtype) function]

Q19. Write a function countNow(PLACES) in Python that takes the dictionary PLACES as an argument and
displays the names (in uppercase) of the places whose names are longer than 5 characters.
For example, if the dictionary PLACES is:

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 21 of 31
Functions in Python Class 12 – Computer Science (083)

PLACES = {1:"Delhi", 2:"Bengaluru", 3:"Pune", 4:"Hyderabad"}

The output should be:

Output:
BENGALURU
HYDERABAD

[Based on CBSE 2023-24 Sample Paper]

Q20. Write a user-defined function in Python named showGrades(S) which takes a dictionary S as an
argument, where S contains Name : [Eng, Math, Science] as key:value pairs. The function should display the
average of the three marks for every student.
[Based on CBSE 2023-24 Board Paper, Set 4]

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 22 of 31
Functions in Python Class 12 – Computer Science (083)

Section D -- 4-5 Mark Questions (Long Answer / Programming)


Q21. The code given below accepts a number as an argument and returns the reversed number. Observe the
code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made:

define revNumber (num) :


rev = 0
rem = 0
While num > 0:
rem == num
rev = rev*10 + rem
num = num//10
return rev
print (revNumber (1234))

[Based on CBSE 2023-24 Board Sample Paper]

Q22. Write a function in Python, PUSH(Package), where Package is a dictionary containing the details of
parcel items -- {ItemName : Weight}. The function should push the names of those items in a list named
StackPkg that have a Weight greater than 50 (kg).
For example, if the dictionary Package is:

Package = {"Fridge":85, "Mixer":15, "Washing Machine":62, "Mobile":1}

The list StackPkg should contain:

Output:
['Fridge', 'Washing Machine']

[Inspired by CBSE stack-via-function pattern, 2022-23]

Q23. Write the definition of a user-defined function INDEX_LIST(L), where L is a list of elements passed as an
argument to the function. The function should return another list named indexList that stores the indices of
all the Non-Zero elements of L.
For example, if L contains:

L = [0, 5, 0, 9, 0, 3]

The indexList should contain:

Output:
[1, 3, 5]

[Based on CBSE 2022-23 Board Sample Paper]

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 23 of 31
Functions in Python Class 12 – Computer Science (083)

Q24. Write a function in Python, findGrade(Marks), that takes the dictionary of student marks, Marks, as an
argument, and returns a new dictionary, ResultDict, that stores the grade obtained by each student
according to the following rule:
• Marks >= 90 -> Grade 'A'
• 75 <= Marks < 90 -> Grade 'B'
• 60 <= Marks < 75 -> Grade 'C'
• Marks < 60 -> Grade 'D'
For example, if the dictionary Marks is {"Aman":95, "Riya":72, "Karan":55}, the function should return
{"Aman":"A", "Riya":"C", "Karan":"D"}.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 24 of 31
Functions in Python Class 12 – Computer Science (083)

Q25. Write a program in Python with the following user-defined functions:


• COURIER_ADD(): Takes details (Code, Destination, Weight) from the user and adds them as a list to a list
named CourierList.
• COURIER_SEARCH(): Takes the destination as input from the user and displays all the courier records
(from CourierList) going to that destination.
Call both functions appropriately to demonstrate their working.
[Based on CBSE 2023 Board Paper]

Q26. (A) Write a user-defined function in Python named showInLines() which reads the contents of a text file
named [Link] and displays every sentence in a separate line. Assume that a sentence ends with a full
stop (.), a question mark (?), or an exclamation mark (!).
For example, if the content of the file [Link] is:

[Link] content:
Computers are powerful. Functions make code reusable! Do you agree?

The function should display:

Output:
Computers are powerful.
Functions make code reusable!
Do you agree?

[Based on CBSE 2024 Board Paper, Q28]

Q27. Write a function in Python, Push(SItem), where SItem is a dictionary containing the details of
stationery items -- {Sname : Price}. The function should push the names of those items onto a stack that
have a Price greater than 75.
Also write the function Pop(Stack) to remove and display the topmost item from the stack, showing "Stack
Empty" if there is nothing to remove.
[Based on CBSE 2022-23 Board Sample Paper]

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 25 of 31
Functions in Python Class 12 – Computer Science (083)

ANSWER KEY
Check your answers only after attempting every question

Section A (1 Mark)
A1. (c) def calc(a=5, b): -- invalid, because the non-default parameter b appears after the default parameter
a.
A2. (c) length and breadth -- both are parameters; length is positional, breadth has a default value.
A3. (b) 20 -- since fun() is called with no argument, the default x=10 is used, and 10*2 = 20.
A4. (b) global
A5. (b) Local
A6. False -- positional parameters must always be written BEFORE default parameters, not after.
A7. Arguments (actual parameters); Parameters (formal parameters).
A8. Output: 20
Explanation: Inside convert(a), a new local variable a is created (a = a + b = 10 + 20 = 30), but this is local to
convert() only. The global a defined outside remains unchanged at 20, so print(a) after the call displays 20.
A9. (c) A is True but R is False -- the Assertion is correctly worded, but the Reasoning has positional and
default arguments in the wrong order (positional arguments must come first, not default arguments).
A10. (a) Both A and R are true, and R is the correct explanation of A.

Section B (2 Marks)
A11.
Local variable: defined inside a function; accessible only within that function. Example: inside def f(): x = 5, x is
local.
Global variable: defined outside all functions; accessible throughout the program. Example: x = 5 written at the
top level of the script, outside any function.

A12. Corrected code (corrections underlined in your answer sheet):

def calcArea(radius):
pi = 3.14
area = pi * radius * radius
print(area)

Corrections: define changed to def; missing colon added after the header; missing colon and indentation added
for the body; print area changed to print(area).

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 26 of 31
Functions in Python Class 12 – Computer Science (083)

A13. Procedural Abstraction means hiding the internal implementation details of a function from its user. The
user only needs to know the function's name, its required inputs, and what it returns, not how it works
internally. Example: using [Link](25), you don't need to know the algorithm used to compute the square
root.

A14. Output:

Output:
15 30

Explanation: value (15) is passed to num. Inside the function, num becomes 30 locally, and this is returned and
stored in newValue. The original variable value remains unchanged at 15 because the function works on a
separate local copy of the parameter.

A15. Any two of: Positional Argument (order/count must match exactly, e.g., f(2,3)); Default Argument (preset
value used if omitted, e.g., def f(a,b=5)); Keyword Argument (passed as name=value, e.g., f(b=3,a=2)); Variable-
Length Argument (collects multiple values, e.g., def f(*x)).

Section C (3 Marks)
A16. Corrected code:

def EvenOdd():
for i in range(5):
num = int(input("Enter a number"))
if num%2 == 0:
print("Even")
else:
print("Odd")
EvenOdd()

Corrections: missing colon after def EvenOdd(); missing closing parenthesis after input(...); num/2==0 changed
to num%2==0 (must use modulus, not division, to test evenness); correct indentation applied throughout.

A17. Output:

Output:
10 30
2 20

Explanation: Inside fun2(), nonlocal x refers to fun1()'s x, changing it to 10. Because of the earlier global y in
fun1(), y=30 inside fun2() updates the module-level y. fun1() then prints x=10, y=30. The outer (module-level)
x=2 was never touched by nonlocal, since nonlocal only affects the nearest enclosing function's scope, not the

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 27 of 31
Functions in Python Class 12 – Computer Science (083)

top level. So the final print shows the original top-level x=2 along with the updated global y=20 at the time
fun1() was entered.

💡 Note for Students


Nested-function scope questions using nonlocal go slightly beyond the core NCERT Class 12 syllabus,
which focuses mainly on local and global scope. This question is included for stretch practice -- focus
primarily on global/local scope questions like A8 and A14 for the board exam.

A18. Sample Solution:

def findType(mtype):
if mtype == 'A':
print("Action")
elif mtype == 'C':
print("Comedy")
else:
print("Other")

A19. Sample Solution:

def countNow(PLACES):
for key in PLACES:
if len(PLACES[key]) > 5:
print(PLACES[key].upper())

A20. Sample Solution:

def showGrades(S):
for name in S:
marks = S[name]
avg = sum(marks) / len(marks)
print(name, ":", avg)

Section D (4-5 Marks)


A21. Corrected code:

def revNumber(num):
rev = 0
rem = 0
while num > 0:
rem = num%10
rev = rev*10 + rem

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 28 of 31
Functions in Python Class 12 – Computer Science (083)

num = num//10
return rev
print(revNumber(1234))

Corrections: define changed to def, and a missing colon added; While changed to lowercase while; rem==num
changed to rem=num%10 (needed the last digit via modulus; == was wrongly used instead of assignment);
correct indentation applied throughout.

A22. Sample Solution:

def PUSH(Package):
StackPkg = []
for item in Package:
if Package[item] > 50:
[Link](item)
return StackPkg

Package = {"Fridge":85, "Mixer":15, "Washing Machine":62, "Mobile":1}


print(PUSH(Package))

Output:
['Fridge', 'Washing Machine']

A23. Sample Solution:

def INDEX_LIST(L):
indexList = []
for i in range(len(L)):
if L[i] != 0:
[Link](i)
return indexList

L = [0, 5, 0, 9, 0, 3]
print(INDEX_LIST(L))

Output:
[1, 3, 5]

A24. Sample Solution:

def findGrade(Marks):
ResultDict = {}
for name in Marks:

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 29 of 31
Functions in Python Class 12 – Computer Science (083)

m = Marks[name]
if m >= 90:
ResultDict[name] = 'A'
elif m >= 75:
ResultDict[name] = 'B'
elif m >= 60:
ResultDict[name] = 'C'
else:
ResultDict[name] = 'D'
return ResultDict

A25. Sample Solution (key logic):

CourierList = []

def COURIER_ADD():
code = input("Enter Code: ")
dest = input("Enter Destination: ")
wt = float(input("Enter Weight: "))
[Link]([code, dest, wt])

def COURIER_SEARCH():
dest = input("Enter Destination to search: ")
for rec in CourierList:
if rec[1] == dest:
print(rec)

COURIER_ADD()
COURIER_SEARCH()

A26. Sample Solution (key logic):

def showInLines():
f = open("[Link]", "r")
text = [Link]()
sentence = ""
for ch in text:
sentence = sentence + ch
if ch in '.?!':
print([Link]())
sentence = ""
[Link]()

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 30 of 31
Functions in Python Class 12 – Computer Science (083)

A27. Sample Solution:

def Push(SItem):
Stack = []
for name in SItem:
if SItem[name] > 75:
[Link](name)
return Stack

def Pop(Stack):
if len(Stack) != 0:
print([Link]())
else:
print("Stack Empty")

💡 Final Exam-Day Reminder


For 3-5 mark function-writing questions, always: (1) use a meaningful function name exactly as asked in
the question, (2) match the parameter names/order to what's specified, (3) include a return or print as
the question demands, and (4) test your logic mentally with the sample data given before moving on.
Partial marks are awarded for correct logic even with minor syntax slips, so always attempt every part.

Amit Yerpude, PGT CS, PM SHRI Kendriya Vidyalaya Dongargarh


Page 31 of 31

You might also like