HANSRAJ SMARAK SENIOR SECONDARY SCHOOL
Dilshad Garden
Session:2025-2026
PRACTICAL FILE
SUBMITTED TO:
Mrs Seema Sharma
(PGT computer science)
SUBMITTED BY:
DIVYANSHU SINGH
ROLL NUMBER:
46
CLASS & SECTION:
XII-E
Working with Functions
1. WAP that generates a series using a function which takes first and the last value of the series. And then
generates four terms that are equidistant. Display the error message if equidistant numbers cannot be
formed.
Answer:
def Series(a, b):
diff = (b - a) // 3
if (b - a) % 3 != 0:
print("Equidistant numbers cannot be formed")
else:
for i in range(4):
print(a + i * diff, end=" ")
Series(1, 7)
2. The function REV( ) that accept a line of text as argument and returns the line in which each word is
reversed. Display both original and reversed line of text.
Answer:
def REV(line):
return " ".join(word[::-1] for word in [Link]())
line = "Hello World"
print("Original:", line)
print("Reversed:", REV(line))
[Link] a UDF EOReplace(L) which accepts list of numbers L as argument and increments all even numbers
by 1 and decrements all of=dd numbers by 1. For eg. if L=[10,20,30,45,39,50], then the output must be [11,
21 31, 44, 38, 51].
Answer:
def bubble_sort(L):
n = len(L)
for i in range(n):
for j in range(0, n-i-1):
if L[j] > L[j+1]:
L[j], L[j+1] = L[j+1], L[j]
return L
def EOReplace(L):
return [x+1 if x%2==0 else x-1 for x in L]
L = [10,20,30,45,39,50]
print("Sorted:", bubble_sort([Link]()))
print("EOReplace:", EOReplace(L))
[Link] a UDF lenFOURword(L), where L is the list of words passed as the argument to the function. The
function return another list indexList that stores the indices all four lettered words from L. For eg. if
L=[‘Dinesh’, “Ramesh”, “Aman”, “Suresh”,”Rani”,”Anil”], the list indexList will have [2,4,5]
Answer:
def insertion_sort_desc(L):
for i in range(1, len(L)):
key = L[i]
j = i-1
while j >=0 and key > L[j]:
L[j+1] = L[j]
j -= 1
L[j+1] = key
return L
def lenFOURword(L):
return [i for i, word in enumerate(L) if len(word)==4]
L = ["Dinesh","Ramesh","Aman","Suresh","Rani","Anil"]
print("Sorted:", insertion_sort_desc([Link]()))
print("Indices of 4-letter words:", lenFOURword(L))
5. The function to find and display all the prime numbers between 2 to N, where N is passed as argument to
the function.
Answer:
def prime_upto_N(N):
for num in range(2, N+1):
for i in range(2, int(num**0.5)+1):
if num % i == 0:
break
else:
print(num, end=" ")
prime_upto_N(50)
Data Files
6. WA menu Driven program to perform the following tasks for the file [Link]:
a. Create
b. Display Whole File
c. Display Words Which Begins With Uppercase Alphabets
d. Exit
Answer: a) def Create_file():
with open("[Link]","w") as f:
line = input("Enter text: ")
[Link](line+"\n")
Create_file()
b) def Display_file():
with open("[Link]") as f:
print([Link]())
Display_file()
c) def Display_uppercase_words():
with open("[Link]") as f:
for word in [Link]().split():
if word[0].isupper():
print(word)
Display_uppercase_words()
7. WA menu Driven program to perform the following tasks for the above created file [Link]:
a. Remove
b. Convert Case
c. Exit
Answer: a) def Remove_word():
word=input("Enter the word to remove:")
with open("[Link]") as f:
data = [Link]()
data = [Link](word,"")
with open("[Link]","w") as f:
[Link](data)
print("/nUpdated file content:")
print(data)
Remove_word()
b) def Convert_case():
with open("[Link]") as f:
data = [Link]()
new_data = [Link]()
with open("[Link]","w") as f:
[Link](new_data)
print("Updated file content:/n")
print(new_data)
Convert_case()
c) while True:
print("/n-----MENU-----")
print("[Link]")
choice = input("Enter your choice(c):")
if [Link]()=="c":
print("Exiting program...")
break
else:
print("Invalid choice! Please press c to exit.")
8. WA menu Driven program to perform the following tasks for the file [Link]:
a. Create
b. Display all
c. Shift Data
d. Exit
Answer: a) def Create_file():
with open("[Link]","w") as f:
line = input("Enter text: ")
[Link](line+"\n")
Create_file()
b) def Display_all():
with open("[Link]") as f:
print([Link]())
Display_all()
c) def Shift_data():
with open("[Link]") as f:
data = [Link]()
upper = "".join([ch for ch in data if [Link]()])
lower = "".join([ch for ch in data if [Link]()])
digit = "".join([ch for ch in data if [Link]()])
with open("[Link]", "w") as f1:
[Link](upper)
with open("[Link]", "w") as f2:
[Link](lower)
with open("[Link]", "w") as f3:
[Link](digit)
print("Uppercase:", upper)
print("Lowercase:", lower)
print("Digits:", digit)
Shift_data()
9. Write a menu driven program to perform the following tasks for a binary file [Link] containing the
following structure: [rno, name, marks, grade]
1. Create
2. Display
3. Calculate Grade
4. Search
5. Exit
Answer: a) import pickle
def Create_student():
with open("[Link]","ab") as f:
rno = int(input("Roll No: "))
name = input("Name: ")
marks = int(input("Marks: "))
rec = [rno,name,marks,""]
[Link](rec,f)
Create_student()
b) import pickle
def Display_students():
try:
with open("[Link]","rb") as f:
while True:
rec = [Link](f)
print(rec)
except:
pass
Display_students()
c) import pickle
def Calculate_grade():
new_records = []
try:
with open("[Link]", "rb") as f:
while True:
try:
rec = [Link](f)
marks = rec[2] / 5
if marks>=90 :grade = "A"
elif marks >= 80:grade = "B+"
elif marks >= 70:grade = "B"
elif marks >= 60: grade = "C+"
elif marks >= 50:grade = "C"
else:
grade = "F"
rec[3] = grade
new_records.append(rec)
except EOFError:
break
except FileNotFoundError:
print("File not found. Please create [Link] first.")
return
with open("[Link]", "wb") as f:
for r in new_records:
[Link](r, f)
if new_records:
print("Grades calculated. Updated records are:")
for r in new_records:
print(f"Roll No: {r[0]}, Name: {r[1]}, Marks: {r[2]}, Grade: {r[3]}")
else:
print("No records found in the file.")
Calculate_grade()
d) import pickle
def Search_student(rno):
with open("[Link]","rb") as f:
try:
while True:
rec = [Link](f)
if rec[0]==rno:
print(rec)
return
except: pass
print("Record Not Found")
rno = int(input("Enter Roll Number to Search: "))
Search_student(rno)
10. Write a menu driven program to perform the following tasks for the above created binary file
[Link].
1. Create
2. Display
3. Search
4. Modify
5. Delete
6. Exit
Answer: a) import pickle, os
def Create_student():
with open("[Link]","ab") as f:
rno = int(input("Roll No: "))
name = input("Name: ")
marks = int(input("Marks: "))
rec = [rno,name,marks,""]
[Link](rec,f)
Create_student()
b) import pickle
def Display_students():
try:
with open("[Link]","rb") as f:
while True:
rec = [Link](f)
print(rec)
except: pass
Display_students()
c) import pickle
def Search_student(rno):
with open("[Link]","rb") as f:
try:
while True:
rec = [Link](f)
if rec[0]==rno:
print(rec)
return
except: pass
print("Record Not Found")
rno = int(input("Enter roll no:"))
Search_student(rno)
e) import pickle
def Delete_student(rno):
new_records=[]
with open("[Link]","rb") as f:
try:
while True:
rec=[Link](f)
if rec[0]!=rno:
new_records.append(rec)
except EOFError:
print("Record not found")
rno=int(input("Enter a roll no"))
Delete_student(rno)
11. Write a Menu Driven Program to create a csv file named [Link] containing rollnumber, name and
phone number. The menu is as follows:
a. Read
b. Write
c. Search
d. Exit
Answer: b) import csv
def Write_csv():
with open("[Link]","a",newline="") as f:
w = [Link](f)
rno = int(input("Roll: "))
name = input("Name: ")
ph = input("Phone: ")
[Link]([rno,name,ph])
[Link]()
Write_csv()
a)import csv
def Read_csv():
with open("[Link]") as f:
r = [Link](f)
for row in r:
print(row)
Read_csv()
c) import csv
def Search_csv(name):
with open("[Link]") as f:
r = [Link](f)
for row in r:
if row[1]==name:
print(row)
name= input("Enter a name:")
Search_csv(name)
12. Write a Menu Driven Program to perform the following tasks in the above created csv file named
[Link]. The menu is as follows:
a. Read
b. Write
c. Modify
d. Delete
Answer: a)done above
b)done above
c) import csv
def Modify_csv(rno):
rows=[]
with open("[Link]") as f:
r=[Link](f)
for row in r:
if row and int(row[0])==rno:
name=input("New Name: ")
ph=input("New Phone: ")
[Link]([rno,name,ph])
else:
[Link](row)
with open("[Link]","w",newline="") as f:
w=[Link](f)
[Link](rows)
rno=int(input("Enter a roll no:"))
Modify_csv(rno)
d) import csv
def Delete_csv(rno):
rows=[]
with open("[Link]") as f:
r=[Link](f)
for row in r:
if row and int(row[0])!=rno:
[Link](row)
with open("[Link]","w",newline="") as f:
w=[Link](f)
[Link](rows)
rno=int(input("Enter a roll number:"))
Delete_csv(rno)
13. Write a Menu Driven Program to perform the following tasks in the csv file named [Link]. The menu is as
follows:
a. Create
b. Display All
c. Search
Answer: a) import csv
def Create_id():
userid=input("Enter userid: ")
password=input("Enter password: ")
if '@' in userid and ([Link]('.com') or [Link]('.[Link]')):
with open("[Link]","a",newline="") as f:
w=[Link](f)
[Link]([userid,password])
Create_id()
b) import csv
def Display_all():
with open("[Link]") as f:
r=[Link](f)
for i,row in enumerate(r,1):
print(i,row)
Display_all()
c)import csv
def Search_id(uid):
with open("[Link]") as f:
r=[Link](f)
for row in r:
if row[0]==uid:
print("Password:",row[1])
uid=input("Enter a id:")
Search_id(uid)
MY SQL and Python Interface
16. Consider the following tables GAMES and PLAYER and answer (b) and (c) parts of this
question:
(b) Write SQL commands for the flowing statements: 103
(i) To display the name of all GAMES with their GCodes
(ii) To display details of those GAMES which are having PrizeMoney more than 7000.
(iii) To display the content of the GAMES table in ascending order of Schedule Date.
(iv) To display sum of PrizeMoney for each Type of GAMES
Answer: i) SELECT GCode, GameName FROM GAMES;
(ii) SELECT * FROM GAMES WHERE PrizeMoney > 7000;
(iii) SELECT * FROM GAMES ORDER BY ScheduleDate;
(iv) SELECT Type, SUM(PrizeMoney) FROM GAMES GROUP BY Type;
17. Consider the following tables Stationary and Consumer. Write SQL commands for the statement (i) to (iv)
and output for SQL queries (v) to (viii):
Table: Stationary
(i) To display the details of those consumers whose Address is Delhi.
(ii) (ii) To display the details of Stationary whose Price is in the range of 8 to 15.
(Both Value included)
(iii) (iii) To display the ConsumerName, Address from Table Consumer, and
Company and Price from table Stationary, with their corresponding matching
S_ID.
(iv) (iv) To increase the Price of all stationary by 2
Answer: i) SELECT * FROM Consumer WHERE Address='Delhi';
(ii) SELECT * FROM Stationary WHERE Price BETWEEN 8 AND 15;
(iii) SELECT ConsumerName, Address, Company, Price FROM Consumer, Stationary
WHERE Consumer.S_ID=Stationary.S_ID;
(iv) UPDATE Stationary SET Price = Price+2;
18. Consider the following table RESORT and OWNER and answer questions (A) and (B)
(A) Write SQL commands for the following statements:
(i) to display the RCODE and PLACE of all ‘2 Star’ resorts in the alphabetical order of
the place from table RESORT.
(ii) to display the maximum & minimum rent for each type of resort from table
RESORT.
(iii) to display the details of all resorts which are started after 31-Dec-04 from table
RESORT.
(iv) to display the owner of all ‘5 Star’ resorts from tables RESORT and OWNEDBY.
Answer: (i) SELECT RCODE, PLACE FROM RESORT WHERE TYPE='2 Star' ORDER BY
PLACE;
(ii) SELECT TYPE, MAX(RENT), MIN(RENT) FROM RESORT GROUP BY TYPE;
(iii) SELECT * FROM RESORT WHERE STARTDATE > '2004-12-31';
(iv) SELECT OWNER FROM RESORT, OWNEDBY WHERE
[Link]=[Link] AND TYPE='5 Star';
Write a python script to implement database connectivity with MySQL.
The script should be menu driven with user defined functions to perform
the following operations:
19. Perform the following operations:
a. Create Database TESTDB
b. Open Database TESTDB
c. Create Table EMP with the following structure:
d. Insert 5 records into EMP table
e. Display all the records of EMP table whose Empno is entered by the user.
Answer:
import [Link] as c
con = [Link](host="localhost",user="root",passwd="DIVYANSHUSINGH")
cur = [Link]()
[Link]("CREATE DATABASE TESTDB")
[Link]("USE TESTDB")
[Link]("CREATE TABLE EMP(Empno INT PRIMARY KEY, Ename VARCHAR(30), Age
INT, Gender CHAR(1), Salary FLOAT)")
[Link]("INSERT INTO EMP VALUES(1,'Aman',25,'M',50000)")
[Link]("SELECT * FROM EMP WHERE Empno=1")
for row in cur:
print(row)
INDEX
SNO TOPIC NO OF PAGE NO DATE OF SIGNATURE
PROGRAMS SUBMISSION
1 FUNCTIONS 5 18-08-2025
2 DATA FILES 8 18-08-2025
3 MY SQL AND
PYTHON 5 18-08-2025
INTERFACE
TOTAL
PROGRAMS 18