CLASS XII COMPUTER SCIENCE PRACTICAL FILE (2025–26)
=========================================================
SECTION 1 – TEXT FILE PROGRAMS
-------------------------------
Q1. Count words that start with ‘the’
-------------------------------------
def count_words_starting_with_the(filename):
count = 0
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
for word in [Link]():
w = [Link]('.,;:!?()"'').lower()
if [Link]('the'):
count += 1
return count
print("Count:", count_words_starting_with_the("[Link]"))
Q2. Count all lines having ‘a’ as the last character
----------------------------------------------------
def count_lines_ending_with_a(filename):
count = 0
with open(filename, 'r') as f:
for line in f:
s = [Link]()
if [Link]().endswith('a'):
count += 1
return count
print("Lines ending with 'a':", count_lines_ending_with_a("[Link]"))
Q3. Count number of digits in [Link]
---------------------------------------
def count_digits_in_file(filename):
digits = 0
with open(filename, 'r') as f:
for line in f:
for ch in line:
if [Link]():
digits += 1
return digits
print("Total digits:", count_digits_in_file("[Link]"))
Q4. Transfer lines starting with a vowel from [Link] to [Link]
-------------------------------------------------------------------
def transfer_lines_starting_with_vowel(origin, newfile):
vowels = 'aeiou'
with open(origin, 'r') as fin, open(newfile, 'a') as fout:
for line in fin:
if line and [Link]() != '' and [Link]()[0].lower() in vowels:
[Link](line)
transfer_lines_starting_with_vowel("[Link]", "[Link]")
print("Transferred successfully.")
Q5. Display words having less than 4 characters from [Link]
-------------------------------------------------------------
def short_words(filename):
with open(filename, 'r') as f:
for line in f:
for word in [Link]():
w = [Link]('.,;:!?()"'')
if len(w) < 4:
print(w)
short_words("[Link]")
SECTION 2 – BINARY FILE PROGRAMS
--------------------------------
Q6. Append Employee records
----------------------------
import pickle
def add_employee():
emp = {}
emp['Empno'] = int(input("Enter Empno: "))
emp['Name'] = input("Enter Name: ")
emp['Address'] = input("Enter Address: ")
emp['Salary'] = float(input("Enter Salary: "))
with open("[Link]", "ab") as f:
[Link](emp, f)
print("Record added successfully!")
add_employee()
Q7. Delete Student record based on Rollno
-----------------------------------------
import pickle, os
def delete_student(rollno):
found = False
with open("[Link]", "rb") as fin, open("[Link]", "wb") as fout:
try:
while True:
record = [Link](fin)
if record['Rollno'] != rollno:
[Link](record, fout)
else:
found = True
except EOFError:
pass
[Link]("[Link]")
[Link]("[Link]", "[Link]")
if found:
print("Record deleted.")
else:
print("Record not found.")
delete_student(int(input("Enter roll no to delete: ")))
Q8. Update marks of Student record
----------------------------------
import pickle, os
def update_marks(rollno, newmarks):
found = False
with open("[Link]", "rb") as fin, open("[Link]", "wb") as fout:
try:
while True:
rec = [Link](fin)
if rec['Rollno'] == rollno:
rec['Marks'] = newmarks
found = True
[Link](rec, fout)
except EOFError:
pass
[Link]("[Link]")
[Link]("[Link]", "[Link]")
if found:
print("Record updated.")
else:
print("Roll number not found.")
update_marks(int(input("Enter roll no: ")), int(input("Enter new marks: ")))
SECTION 3 – CSV FILE PROGRAMS
------------------------------
Q9. Display patients with cholesterol >250 and Resting BP <125
--------------------------------------------------------------
import csv
with open("[Link]", "r") as f:
r = [Link](f)
for row in r:
if int(row['Cholesterol']) > 250 and int(row['RestingBP']) < 125:
print(row)
Q10. Display blood sugar for patients whose name starts with 'O' or ends with 'r' and age >70
---------------------------------------------------------------------------------------------
import csv
with open("[Link]", "r") as f:
r = [Link](f)
for row in r:
name = row['Name']
if ([Link]('O') or [Link]('r')) and int(row['Age']) > 70:
print("Name:", name, "Blood Sugar:", row['BloodSugar'])
Q11. Display each row in reverse order
--------------------------------------
import csv
with open("[Link]", "r") as f:
data = list([Link](f))
for row in data:
print(row[::-1])
SECTION 4 – LIST, STRING & DICTIONARY
-------------------------------------
Q12. Frequency of each alphabet in a string
-------------------------------------------
def freq(s):
s = [Link]()
print("Alphabet\tFrequency")
for ch in sorted(set(s)):
if [Link]():
print(ch, "\t\t", [Link](ch))
freq(input("Enter string: "))
Q13. Display only duplicate elements from a list
------------------------------------------------
def duplicate_list(lst):
dup = []
for i in lst:
if [Link](i) > 1 and i not in dup:
[Link](i)
return dup
lst = [10, 20, 30, 10, 40, 20, 50]
print("Duplicate elements:", duplicate_list(lst))
Q14. Sort string in descending order using Bubble Sort
------------------------------------------------------
def bubble_sort_desc(word):
lst = list(word)
n = len(lst)
for i in range(n):
for j in range(0, n - i - 1):
if lst[j] < lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return ''.join(lst)
print(bubble_sort_desc(input("Enter string: ")))
Q15. Subtract values of two dictionaries
----------------------------------------
def subtract_dict(d1, d2):
d3 = {}
for k in d1:
if k in d2:
d3[k] = abs(d1[k] - d2[k])
return d3
d1 = {'gfg':6, 'is':4, 'best':7}
d2 = {'gfg':10, 'is':6, 'best':10}
print("Difference dictionary:", subtract_dict(d1, d2))
SECTION 5 – PYTHON–MYSQL INTERFACE
----------------------------------
Q16. Insert and display Employee table
--------------------------------------
import [Link] as sql
con = [Link](host="localhost", user="root", password="root", database="school")
cur = [Link]()
[Link]("INSERT INTO employee VALUES (101,'Ravi','Sales',35000)")
[Link]()
[Link]("SELECT * FROM employee")
for i in cur:
print(i)
[Link]()
Q17. Search Employee record based on empno
------------------------------------------
import [Link] as sql
con = [Link](host="localhost", user="root", password="root", database="school")
cur = [Link]()
eno = int(input("Enter empno: "))
[Link](f"SELECT * FROM employee WHERE empno={eno}")
for r in cur:
print(r)
[Link]()
Q18. Update Employee salary based on empno
------------------------------------------
import [Link] as sql
con = [Link](host="localhost", user="root", password="root", database="school")
cur = [Link]()
eno = int(input("Enter empno: "))
sal = float(input("Enter new salary: "))
[Link](f"UPDATE employee SET salary={sal} WHERE empno={eno}")
[Link]()
print("Updated successfully!")
[Link]()
Q19. Delete Employee record based on empno
------------------------------------------
import [Link] as sql
con = [Link](host="localhost", user="root", password="root", database="school")
cur = [Link]()
eno = int(input("Enter empno to delete: "))
[Link](f"DELETE FROM employee WHERE empno={eno}")
[Link]()
print("Record deleted.")
[Link]()
SECTION 6 – SQL QUERIES
------------------------
Q20. Table: Prepaid
--------------------
(i) SELECT * FROM Prepaid WHERE Connection IN ('Jio','Vodafone');
(ii) SELECT DISTINCT Connection FROM Prepaid;
(iii) SELECT Connection, MAX(Plan) FROM Prepaid GROUP BY Connection;
(iv) SELECT Model, COUNT(*) FROM Prepaid GROUP BY Model;
(v) SELECT * FROM Prepaid WHERE Custname LIKE '%k';
Q21. Table: Stock
-----------------
(i) SELECT * FROM Stock ORDER BY stockdate ASC;
(ii) SELECT dcode, MAX(unitprice) FROM Stock GROUP BY dcode;
(iii) SELECT * FROM Stock ORDER BY item DESC;
(iv) SELECT dcode, AVG(unitprice) FROM Stock GROUP BY dcode HAVING AVG(unitprice) > 5;
(v) SELECT dcode, SUM(qty) FROM Stock GROUP BY dcode;
Q22. Table: Club
----------------
(a) SELECT Coach_Name FROM Club WHERE Coach_Name LIKE 'A%H';
(b) SELECT SUM(Pay) FROM Club WHERE Sports='SWIMMING';
(c) SELECT Coach_Name, Age FROM Club ORDER BY Age DESC;
(d) UPDATE Club SET Pay = Pay + (Pay * 0.10);
(e) ALTER TABLE Club DROP PRIMARY KEY; ALTER TABLE Club ADD PRIMARY KEY (Coach_Name);
(f) DELETE FROM Club WHERE Sports='SWIMMING';
(g) ALTER TABLE Club ADD Gender CHAR(1);
Q23. Table: Product
-------------------
(h) SELECT PRODUCT FROM Product WHERE PRODUCT LIKE '%R';
(i) SELECT * FROM Product WHERE NUMBER_OF_ITEMS < 50;
(j) SELECT PRODUCT, TOTAL_PRICE FROM Product ORDER BY TOTAL_PRICE DESC;
(k) ALTER TABLE Product DROP PRIMARY KEY; ALTER TABLE Product ADD PRIMARY KEY (PRODUCT);
(l) UPDATE Product SET NUMBER_OF_ITEMS = NUMBER_OF_ITEMS + (NUMBER_OF_ITEMS * 0.10);
(m) DELETE FROM Product WHERE TOTAL_PRICE < 5000;
(n) ALTER TABLE Product ADD Date_of_manufacture DATE;