Functions in Python Notes
Functions in Python Notes
FUNCTIONS IN PYTHON
Complete Study Notes • Class 12 – CBSE 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).
def greet():
print("Hello, welcome to Python functions!")
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.
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
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
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.
Output:
8
<class 'int'>
9
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
def isEven(n):
if n % 2 == 0:
return True
else:
return False
print(isEven(10))
print(isEven(7))
Output:
True
False
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.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.
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
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.
⚠️ 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.
Output:
Riya is 24 years old, earns Rs. 45000
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.
A second example showing the invalid ordering, exactly the kind of ‘find the error’ question CBSE asks:
Output:
25
32
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.
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.
⚠️ 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.
def sayhello(name):
message = "hello " + name
return message
m = sayhello("amit")
print(m)
Output:
hello amit
def minMax(numbers):
return min(numbers), max(numbers)
Output:
Smallest: 5
Largest: 67
def showMessage():
print("Processing complete.")
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.
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.
Output:
30
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.
Built-in function Already defined in Python; ready to use (print, len, type).
Function Header First line; starts with def, ends with a colon.
Positional argument Order & count must exactly match the definition.
Default argument Has a preset value, used only if the call omits it.
return statement Sends a value back to the caller; ends execution immediately.
global keyword Lets a function modify a global variable instead of creating a local copy.
• 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.
PRACTICE QUESTIONS
Based on CBSE Class 12 Computer Science (083) Board Exam Patterns
Q2. Identify the parameter(s) in the following function header: def findArea(length, breadth=10):
(a) length only
(d) findArea
(b) 20
(c) Error
(d) None
Q4. Which keyword is used to access and modify a global variable inside a function in Python?
(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
a = 20
def convert(a):
b = 20
a = a + b
convert(10)
print(a)
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)
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.
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
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.
def EvenOdd()
for i in range (5):
num=int (input ("Enter a number")
if num/2==0:
print ("Even")
else:
print ("Odd")
EvenOdd()
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)
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:
Output:
BENGALURU
HYDERABAD
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]
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:
Output:
['Fridge', 'Washing Machine']
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]
Output:
[1, 3, 5]
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"}.
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?
Output:
Computers are powerful.
Functions make code reusable!
Do you agree?
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]
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.
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).
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
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.
def findType(mtype):
if mtype == 'A':
print("Action")
elif mtype == 'C':
print("Comedy")
else:
print("Other")
def countNow(PLACES):
for key in PLACES:
if len(PLACES[key]) > 5:
print(PLACES[key].upper())
def showGrades(S):
for name in S:
marks = S[name]
avg = sum(marks) / len(marks)
print(name, ":", avg)
def revNumber(num):
rev = 0
rem = 0
while num > 0:
rem = num%10
rev = rev*10 + rem
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.
def PUSH(Package):
StackPkg = []
for item in Package:
if Package[item] > 50:
[Link](item)
return StackPkg
Output:
['Fridge', 'Washing Machine']
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]
def findGrade(Marks):
ResultDict = {}
for name in Marks:
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
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()
def showInLines():
f = open("[Link]", "r")
text = [Link]()
sentence = ""
for ch in text:
sentence = sentence + ch
if ch in '.?!':
print([Link]())
sentence = ""
[Link]()
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")