Class | Subject | Book | Chapter | Session | Questions covered |
|---|---|---|---|---|---|
XI | Computer Science | Computer Science (NCERT) | 7 – Functions | 2026-27 | 8 of 8 |
Chapter at a glance
Idea | Key point |
|---|---|
Function | Named group of statements that performs a task; called when needed |
Advantages | Modularity, reusability, readability, easier testing and debugging |
Definition | def name(parameters): followed by an indented body; return sends back a value |
Arguments | Values passed in a call; parameters are the names in the definition; default parameters allowed |
Scope | Local variables exist only inside the function; global variables throughout the program (global keyword to modify) |
Built-in functions | print(), len(), input(), int(), abs(), max() … |
Modules | Files of functions: import math, from random import randint; user-defined modules imported the same way |
random module | random(), randint(a, b), randrange(), shuffle(), sample() |
Exercise Questions
Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.
Answer
Answer
def divisible_by_7(num):
if num % 7 == 0:
print(num, "is divisible by 7")
else:
print(num, "is not divisible by 7")
n = int(input("Enter a number: "))
divisible_by_7(n)
Sample run: 91 → 91 is divisible by 7; 50 → 50 is not divisible by 7
A function divisible_by_7(num) checks num % 7 == 0 and prints the result.
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
Answer
def add_prefix(name, gender):
if gender.upper() == 'M':
return "Mr " + name
elif gender.upper() == 'F':
return "Ms " + name
else:
return name
name = input("Enter name: ")
gender = input("Enter gender (M/F): ")
print(add_prefix(name, gender))
Sample run: Anil, M → Mr Anil; Kavya, F → Ms Kavya
add_prefix(name, gender) returns “Mr” + name for M and “Ms” + name for F.
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 b²−4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.
Answer
Answer
(The quantity b² − 4ac is called the discriminant.)
def discriminant(a, b, c):
d = b * b - 4 * a * c
if d > 0:
print("D =", d, ": two distinct real roots")
elif d == 0:
print("D =", d, ": two equal real roots")
else:
print("D =", d, ": no real roots (roots are complex)")
return d
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
discriminant(a, b, c)
Sample runs: (1, −5, 6) → D = 1, distinct real roots; (1, 2, 1) → D = 0, equal roots; (1, 1, 1) → D = −3, no real roots.
Compute D = b² − 4ac in a function; D > 0 → two distinct real roots, D = 0 → equal roots, D < 0 → no real roots.
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
Answer
import random
def lucky_draw():
return random.randint(1, 600) # both 1 and 600 included
print("The winning token number is:", lucky_draw())
Each run picks a random token between 1 and 600, e.g. The winning token number is: 347.
Use random.randint(1, 600) to pick and print the winning token ID.
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
Answer
The hint gives the amount; compound interest = amount − principal. Rate r is used as a fraction (R/100).
def compound_interest(P, R, T, n):
r = R / 100
amount = P * (1 + r / n) ** (n * T)
ci = amount - P
print("Amount =", round(amount, 2))
print("Compound interest =", round(ci, 2))
P = float(input("Principal: "))
R = float(input("Rate (% per annum): "))
T = float(input("Time (years): "))
n = int(input("Times compounded per year: "))
compound_interest(P, R, T, n)
Sample run: P = 10000, R = 10, T = 2, n = 1 → Amount = 12100.0, CI = 2100.0
amount = P(1 + r/n)nt with r = R/100, and CI = amount − P (e.g. ₹ 10000 at 10 % for 2 years yearly → CI = ₹ 2100).
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 returned in place of number 2, otherwise the same order is returned.
Answer
Answer
def order(num1, num2):
if num1 < num2:
return num2, num1
return num1, num2
a = int(input("Enter number 1: "))
b = int(input("Enter number 2: "))
a, b = order(a, b)
print("Number 1 =", a, "Number 2 =", b)
Sample runs: (3, 8) → Number 1 = 8 Number 2 = 3; (9, 4) → Number 1 = 9 Number 2 = 4
The function returns (num2, num1) if num1 < num2, otherwise (num1, num2) — Python can return two values as a tuple.
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
Answer
Module file shapes.py
import math
def square_area(s): return s * s
def square_perimeter(s): return 4 * s
def rectangle_area(l, b): return l * b
def rectangle_perimeter(l, b): return 2 * (l + b)
def triangle_area(a, b, c): # Heron's formula
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def triangle_perimeter(a, b, c): return a + b + c
def circle_area(r): return math.pi * r * r
def circle_perimeter(r): return 2 * math.pi * r
def cylinder_surface_area(r, h): return 2 * math.pi * r * (r + h)
def cylinder_volume(r, h): return math.pi * r * r * h
Main program main.py
import shapes
print("Square (side 4): area", shapes.square_area(4), "perimeter", shapes.square_perimeter(4))
print("Rectangle (5 x 3): area", shapes.rectangle_area(5, 3),
"perimeter", shapes.rectangle_perimeter(5, 3))
print("Triangle (3, 4, 5): area", shapes.triangle_area(3, 4, 5),
"perimeter", shapes.triangle_perimeter(3, 4, 5))
print("Circle (r 7): area", round(shapes.circle_area(7), 2),
"circumference", round(shapes.circle_perimeter(7), 2))
print("Cylinder (r 7, h 10): surface area", round(shapes.cylinder_surface_area(7, 10), 2))
Output: square 16, 16; rectangle 15, 16; triangle 6.0, 12; circle 153.94, 43.98; cylinder 747.7.
Put the shape functions (each taking parameters and returning a value) in a module shapes.py, then import shapes in the main program and call shapes.circle_area(7), etc.
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: 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.
Answer
Answer
import random
questions = [
("What is the capital of India?", "new delhi"),
("Which planet is known as the Red Planet?", "mars"),
("Who wrote the national anthem of India?", "rabindranath tagore"),
("What is the largest ocean on Earth?", "pacific"),
("How many states are there in India?", "28"),
]
def score():
random.shuffle(questions) # display in random order
marks = 0
for q, ans in questions:
reply = input(q + " ").strip().lower()
if reply == ans:
marks += 1
return marks
def remark(scorevalue):
remarks = {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."}
print("Score:", scorevalue, "-", remarks[scorevalue])
remark(score())
Store five (question, answer) pairs, shuffle them with random.shuffle(), let score() ask each and count correct replies, and remark(scorevalue) print the remark for that score.
Case study 7.2 (SMIS): short-attendance function
def short_attendance(days_present, working_days):
percent = days_present / working_days * 100
return 1 if percent < 78 else 0
wd = int(input("Total working days in the month: "))
dp = int(input("Days present: "))
if short_attendance(dp, wd) == 1:
print("Short attendance (defaulter)")
else:
print("Attendance is not short")
Topic checklist
- ☒ Defining and calling functions with parameters (Q1–3, 6)
- ☒ Returning values, including multiple values (Q6, 7)
- ☒ random module (Q4, 8)
- ☒ User-defined modules (Q7)