NCERT Solutions For Class 12 Computer Science
Chapter 7 – Functions
Exercise
Question 1: Observe the following programs carefully, and identify the
error:
a) def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call
b) from math import sqrt,ceil
def calc():
print cos(0)
calc() #function call
c) mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function call
d) def findValue( vall = 1.1, val2, val3):
final = (val2 + val3)/ vall
print(final)
[Link] 1
findvalue() #function call
e) def greet():
return("Good morning")
greet() = message #function call
Answer:
● (a) Indentation + call signature error: the loop body must be
indented; also create(5) is missing the text argument. Python 3
needs print().
def create(text, freq):
for i in range(1, freq):
print(text)
create("Hello", 5)
● (b) Missing import for cos + Python 3 print: you imported sqrt, ceil
but used cos. Import it or use [Link].
from math import sqrt, ceil, cos
def calc():
print(cos(0))
calc()
[Link] 2
● (c) UnboundLocalError: assignment to mynum inside the function
makes it local; either declare global or use a parameter/return
value.
# Option 1 (use return):
def add9(n):
n = n + 9
print(n)
return n
mynum = 9
mynum = add9(mynum)
● (d) Default parameter order + case-sensitive call: parameters with
defaults must come after non-defaults; function is called as
findvalue() (wrong case).
def findValue(val2, val3, vall=1.1):
final = (val2 + val3) / vall
print(final)
findValue(10, 22)
● (e) Cannot assign to a function call: you should assign the return
value to a variable.
def greet():
[Link] 3
return "Good morning"
message = greet()
print(message)
Question 2: How is [Link](89.7) different from [Link] (89.7)?
Answer: [Link](89.7) returns the smallest integer ≥ 89.7 → 90.
[Link](89.7) returns the largest integer ≤ 89.7 → 89.
Question 3: Out of random() and randint(), which function should we use
to generate random numbers between 1 and 5. Justify.
Answer: Use randint(1, 5) because it returns an integer in the inclusive
range [1, 5]. random() returns a float in [0.0, 1.0). While you could
scale/shift it, randint (or randrange(1,6)) is precise and simpler.
Question 4: How is built-in function pow() function different from
function [Link]() ? Explain with an example.
Answer: pow() is a built-in that supports the optional modulus (pow(a, b,
m)) and preserves integers for exact integer powers; it also works with
complex numbers. [Link]() converts arguments to floats and returns a
float, no modulus.
pow(2, 3, 5) # 3 (works)
# [Link](2, 3, 5) -> TypeError (no 3-arg version)
[Link] 4
pow(9, 2) # 81 (int)
[Link](9, 2) # 81.0 (float)
Question 5: Using an example show how a function in Python can return
multiple values.
def stats(a, b, c):
s = a + b + c
avg = s / 3
mn = min(a, b, c)
mx = max(a, b, c)
return s, avg, mn, mx
total, mean, lo, hi = stats(5, 8, 2)
Question 6: Differentiate between following with the help of an example:
a) Argument and Parameter
b) Global and Local variable
Answer:
a. Argument vs Parameter: Parameters are placeholders in the
function definition; arguments are actual values passed in the call.
def greet(name): # 'name' is a parameter
print("Hi", name)
[Link] 5
greet("Asha") # "Asha" is an argument
b. Global vs Local: A global variable is defined at module level; a local
exists within a function scope.
count = 0 # global
def inc():
global count
count += 1 # modifies global
x = 10 # local to inc()
inc()
# print(x) -> NameError: x is local inside inc()
Question 7: Does a function always return a value? Explain with an
example.
Answer: If a function has no return (or returns without a value), it implicitly
returns None.
def demo():
print("Hello") # no explicit return
res = demo() # prints "Hello"
print(res) # None
[Link] 6
Activity-based Questions
Note: Writing a program implies:
• Adding comments as part of documentation
• Writing function definition
• Executing the function through a function call
Question 1: To secure your account, whether it be an email, online bank
account or any other account, it is important that we use authentication.
Use your programming expertise to create a program using user defined
function named login that accepts userid and password as parameters
(login(uid,pwd)) that displays a message “account blocked” in case of
three wrong attempts. The login is successful if the user enters user ID as
"ADMIN" and password as "St0rE@1". On successful login, display a
message “login successful”.
Answer:
def login(uid_expected="ADMIN", pwd_expected="St0rE@1"):
"""
Prompts user up to 3 attempts. Blocks on 3 wrong tries.
"""
attempts = 0
while attempts < 3:
uid = input("User ID: ").strip()
pwd = input("Password: ").strip()
if uid == uid_expected and pwd == pwd_expected:
print("login successful")
[Link] 7
return True
else:
attempts += 1
print(f"Invalid credentials. Attempts left: {3 - attempts}")
print("account blocked")
return False
# Example call:
# login()
Question 2: XYZ store plans to give festival discount to its customers. The
store management has decided to give discount on the following
criteria:
Shopping Amount Discount Offered
Shopping Amount Discount Offered
>=500 and <1000 5%
>=1000 and <2000 8%
>=2000 10%
An additional discount of 5% is given to customers who are the members
of the store. Create a program using user defined function that accepts
[Link] 8
the shopping amount as a parameter and calculates discount and net
amount payable on the basis of the following conditions:
Net Payable Amount = Total Shopping Amount – Discount.
Answer:
def net_payable(amount, is_member=False):
"""
Returns (discount, net_amount) based on slabs + member extra 5%.
"""
if amount < 0:
raise ValueError("Amount must be non-negative")
if amount >= 2000:
base = 0.10
elif amount >= 1000:
base = 0.08
elif amount >= 500:
base = 0.05
else:
base = 0.0
extra = 0.05 if is_member else 0.0
rate = base + extra
discount = amount * rate
net = amount - discount
return round(discount, 2), round(net, 2)
[Link] 9
# Example:
# d, n = net_payable(1200, True)
Question 3: ‘ ’ strategy helps toddlers understand concepts in a fun way.
Being a senior student you have taken responsibility to develop a
program using user defined functions to help children master two and
three-letter words using English alphabets and addition of single digit
numbers. Make sure that you perform a careful analysis of the type of
questions that can be included as per the age and curriculum.
Answer: (Sample interactive drills for 2/3-letter words and single-digit
addition.)
import random
TWO_LETTER =
["am","an","as","at","be","do","go","he","in","it","me","no","on","up","we"]
THREE_LETTER =
["cat","dog","sun","map","pen","bag","cap","jam","pot","red","bed","cup"]
def word_drill(n=5, length=2):
words = TWO_LETTER if length == 2 else THREE_LETTER
score = 0
for _ in range(n):
w = [Link](words)
ans = input(f"Spell this word: {w} (type it) ")
if [Link]().lower() == w:
[Link] 10
print("Great!")
score += 1
else:
print(f"Try again. Correct: {w}")
print(f"Word drill score: {score}/{n}")
def add_drill(n=5):
score = 0
for _ in range(n):
a, b = [Link](0,9), [Link](0,9)
ans = input(f"{a} + {b} = ")
if [Link]().isdigit() and int(ans) == a+b:
print("Nice!")
score += 1
else:
print(f"Oops. It's {a+b}.")
print(f"Addition score: {score}/{n}")
# Example:
# word_drill(5, length=2); word_drill(5, length=3); add_drill(5)
Question 4: Take a look at the series below:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
To form the pattern, start by writing 1 and 1. Add them together to get 2.
Add the last two numbers: 1+2 = [Link] adding the previous two
[Link] 11
numbers to find the next number in the series. These numbers make up
the famed Fibonacci sequence: previous two numbers are added to get
the immediate new number.
Answer:
def fibonacci(n):
"""Return list of first n Fibonacci numbers starting 1, 1, 2, ..."""
if n <= 0: return []
if n == 1: return [1]
seq = [1, 1]
while len(seq) < n:
[Link](seq[-1] + seq[-2])
return seq
# Example: print(fibonacci(10)) -> [1,1,2,3,5,8,13,21,34,55]
Question 5: Create a menu driven program using user defined functions
to implement a calculator that performs the following:
a) Basic arithmetic operations(+,-,*,/)
b) log10(x),sin(x),cos(x)
Answer:
import math
def add(a,b): return a+b
def sub(a,b): return a-b
[Link] 12
def mul(a,b): return a*b
def div(a,b): return a/b
def sci_log10(x): return math.log10(x)
def sci_sin(x): return [Link](x)
def sci_cos(x): return [Link](x)
def calculator():
menu = """
1) Add
2) Subtract
3) Multiply
4) Divide
5) log10(x)
6) sin(x)
7) cos(x)
0) Exit
Choose: """
while True:
ch = input(menu).strip()
if ch == "0": break
try:
if ch in {"1","2","3","4"}:
a = float(input("a = "))
b = float(input("b = "))
res = {"1":add,"2":sub,"3":mul,"4":div}[ch](a,b)
[Link] 13
elif ch == "5":
x = float(input("x = "))
res = sci_log10(x)
elif ch == "6":
x = float(input("x (radians) = "))
res = sci_sin(x)
elif ch == "7":
x = float(input("x (radians) = "))
res = sci_cos(x)
else:
print("Invalid choice"); continue
print("Result:", res)
except Exception as e:
print("Error:", e)
# Example: calculator()
Suggested Lab. Exercises
Question 1: Write a program to check the divisibility of a number by 7 that
is passed as a parameter to the user defined function.
Answer:
def is_divisible_by_7(n):
return n % 7 == 0
# Example:
[Link] 14
# print(is_divisible_by_7(21)) # True
# print(is_divisible_by_7(20)) # False
Question 2: Write a program that uses a user defined function that
accepts name and gender (as M for Male, F for Female) and prefixes
Mr/Ms on the basis of the gender.
Answer:
def prefix_name(name, gender):
gender = [Link]().upper()
if gender == "M":
return f"Mr {name}"
elif gender == "F":
return f"Ms {name}"
else:
return name # or raise ValueError
# Example: print(prefix_name("Asha", "F")) -> Ms Asha
Question 3: Write a program that has a user defined function to accept
the coefficients of a quadratic equation in variables and calculates its
determinant. For example : if the coefficients are stored in the variables
a,b,c then calculate determinant as b2-4ac. Write the appropriate
condition to check determinants on positive, zero and negative and
output appropriate result.
Answer:
[Link] 15
def discriminant(a, b, c):
D = b*b - 4*a*c
if D > 0:
nature = "Two distinct real roots"
elif D == 0:
nature = "One real root (repeated)"
else:
nature = "Complex conjugate roots"
return D, nature
# Example:
# print(discriminant(1, -3, 2)) -> (1, 'Two distinct real roots')
Question 4: ABC School has allotted unique token IDs from (1 to 600) to all
the parents for facilitating a lucky draw on the day of their Annual day
function. The winner would receive a special prize. Write a program
using Python that helps to automate the task.(Hint: use random module)
Answer:
import random
def pick_winner(start=1, end=600):
return [Link](start, end)
# Example: print("Winner token:", pick_winner())
[Link] 16
Question 5: Write a program that implements a user defined function
that accepts Principal Amount, Rate, Time, Number of Times the interest
is compounded to calculate and displays compound interest. (Hint:
CI=P*(1+r/n)nt)
Answer:
def compound_interest(P, r, t, n):
"""
P = principal, r = annual rate in decimal (e.g., 0.08 for 8%),
t = time in years, n = compounding per year.
Returns (Amount, CompoundInterest)
"""
A = P * (1 + r/n) ** (n*t)
CI = A - P
return round(A, 2), round(CI, 2)
# Example:
# print(compound_interest(1000, 0.08, 2, 4))
Question 6: Write a program that has a user defined function to accept 2
numbers as parameters, if number 1 is less than number 2 then numbers
are swapped and returned, i.e., number 2 is returned in place of number1
and number 1 is reformed in place of number 2, otherwise the same order
is returned.
Answer:
[Link] 17
def swap_if_needed(a, b):
return (b, a) if a < b else (a, b)
# Example:
# print(swap_if_needed(3, 9)) -> (9, 3)
# print(swap_if_needed(9, 3)) -> (9, 3)
Question 7: Write a program that contains user defined functions to
calculate area, perimeter or surface area whichever is applicable for
various shapes like square, rectangle, triangle, circle and cylinder. The
user defined functions should accept the values for calculation as
parameters and the calculated value should be returned. Import the
module and use the appropriate functions.
Answer:
# [Link] (module)
import math
def square_area(a): return a*a
def square_perimeter(a): return 4*a
def rectangle_area(l,w): return l*w
def rectangle_perimeter(l,w): return 2*(l+w)
def triangle_area(b,h): return 0.5*b*h
[Link] 18
def circle_area(r): return [Link]*r*r
def circle_circumference(r): return 2*[Link]*r
def cylinder_surface_area(r,h):
return 2*[Link]*r*h + 2*[Link]*r*r
# [Link]
# from shapes import *
# print(circle_area(3))
Question 8: Write a program that creates a GK quiz consisting of any five
questions of your choice. The questions should be displayed randomly.
Create a user defined function score() to calculate the score of the quiz
and another user defined function remark (scorevalue) that accepts the
final score to display remarks as follows:
Marks Remarks
5 Outstanding
4 Excellent
3 Good
2 Read more to score more
1 Needs to take interest
[Link] 19
General knowledge will always help you.
0
Take it seriously.
Answer:
import random
QUESTIONS = [
("Capital of India?", "new delhi"),
("Planet known as Red Planet?", "mars"),
("Largest ocean?", "pacific"),
("National animal of India?", "tiger"),
("Language with most native speakers?", "mandarin"),
]
def score():
qs = [Link](QUESTIONS, k=5)
s = 0
for q, ans in qs:
user = input(q + " ").strip().lower()
if user == ans:
print("Correct!")
s += 1
else:
print("Incorrect. Answer:", [Link]())
return s
[Link] 20
def remark(scorevalue):
mapping = {
5: "Outstanding",
4: "Excellent",
3: "Good",
2: "Read more to score more",
1: "Needs to take interest",
0: "General knowledge will always help you. Take it seriously."
}
return [Link](scorevalue, "Invalid score")
# Example:
# s = score(); print("Score:", s, "-", remark(s))
Case Study-based Question
Question 1: For the SMIS system extended in Chapter 6 let us do the
following:
1. 7.1 Convert all the functionality in Chapter 5 and 6 using user defined
functions.
Answer: Refactor each feature (e.g., add_student, edit_student,
delete_student, record_marks, compute_grade, print_report,
search_student) into separate functions that accept clear parameters
and return values without using input()/print() inside the core logic. Keep
I/O (menus, prompts) in a thin wrapper. Example:
[Link] 21
# [Link]
def add_student(db, roll, name, cls):
if roll in db: return False
db[roll] = {"name": name, "class": cls, "marks": {}}
return True
def record_marks(db, roll, subject, marks):
if roll not in db: return False
db[roll]["marks"][subject] = marks
return True
def compute_percentage(marks_dict):
if not marks_dict: return 0.0
total = sum(marks_dict.values())
return total / (len(marks_dict) * 100) * 100
# [Link] would import core functions and provide menus.
Question 2: 7.2 Add another user defined function to the above menu to
check if the student has short attendance or not. The function should
accept total number of working days in a month and check if the student
is a defaulter by calculating his or her attendance using the formula:
Count of days the student was present or the total number of working
days. In case the attendance calculated is less than 78%, the function
should return 1 indicating short attendance otherwise the function
should return 0 indicating attendance is not short. Let’s peer review the
[Link] 22
case studies of others based on the parameters given under
“DOCUMENTATION TIPS” at the end of Chapter 5 and provide a feedback
to them.
Answer:
def attendance_flag(days_present, working_days):
"""
Returns 1 if attendance < 78%, else 0.
"""
if working_days <= 0:
raise ValueError("working_days must be positive")
pct = (days_present / working_days) * 100
return 1 if pct < 78 else 0
# Example:
# For 18/25 = 72% -> returns 1 (short attendance)
[Link] 23