CBSE Class 12 Computer Science Mid Term Question Paper 2025-26 with Solutions (Morning Shift)
Complete Section A Interactive Questions with Explanations
"ATTENDANCE.CSV" and prints "WARNING" if average attendance is below 75% otherwise prints "OK".Records in
"ATTENDANCE.CSV" are in format:[Name, Total_Attendance, Max_Attendance, Phone]Note: Average attendance = Total_Attendance / Max_Attendance
import csv
with open("ATTENDANCE.CSV", "r") as f:
reader = csv.reader(f)
for row in reader:
name = row[0]
total_att = float(row[1])
max_att = float(row[2])
avg_att = (total_att / max_att) * 100
if avg_att < 75:
print(f"{name}: WARNING")
else:
print(f"{name}: OK")
HURRY() in python that reads the content of a text file "abc.txt" and print one word randomly from each line.
END() in python that reads the content of a text file "xyz.txt" and count the number of words starting and ending with a vowel.
import random
def HURRY():
with open("abc.txt", "r") as f:
lines = f.readlines()
for line in lines:
words = line.split()
if words:
print(random.choice(words))
def END():
vowels = "aeiouAEIOU"
count = 0
with open("xyz.txt", "r") as f:
text = f.read()
words = text.split()
for w in words:
if w[0] in vowels and w[-1] in vowels:
count += 1
print("Count of words:", count)
N=int(input("Give a number"))
a=1
while N>a:
if N%5==0 or N%7==0:
print(a, end=" ")
N+=1
N = int(input("Give a number: "))
a = 1
while N >= a: # Error 1: Condition changed from '>' to '>='
if N % 5 == 0 and N % 7 == 0: # Error 2: Changed 'or' to 'and'
print(N, end=" ") # Error 3: Printed N instead of a
N -= 1 # Error 4: Decremented N instead of incrementing
MULTIPLE(data, n) that prints all keys of data whose values are multiples of n. Here, data is a dictionary.
FUN(N, A) in python that takes numbers N and A as an argument and creates a list L of all the numbers from 1 to N (including 1 and N) where numbers are not multiple of A.
def MULTIPLE(data, n):
for key, value in data.items():
if value % n == 0:
print(key)
def FUN(N, A):
L = []
for i in range(1, N + 1):
if i % A != 0:
L.append(i)
return L
Yes, it can still be read in Python using the csv.reader() method by specifying the delimiter=';' parameter.
import csv
with open("filename.csv", "r") as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
print(row)
I would choose a CSV (Comma-Separated Values) file.
Reason: CSV files are universally supported by tabular file formats like MS Excel, easy to handle in Python, lightweight, and store data in structured tabular rows and columns.
a) The else block is executed only when the if condition is ________.
b) To check if two conditions are both true, we combine them using the ________ logical operator.
a) False
b) and
Write a program in python to handle this using try-except so the user is asked to re-enter a valid number?
while True:
try:
qty = int(input("Enter quantity: "))
print("Quantity entered successfully:", qty)
break
except ValueError:
print("Invalid input! Please re-enter a valid integer number.")
a) The a+ mode opens a file for both appending and writing.
b) The readlines() method returns the content of a file as a list of integers.
c) Reading a text file twice using read() function without using seek() will return an empty string the second time.
a) False (a+ mode opens for both appending and reading).
b) False (It returns a list of strings/lines).
c) True (The file pointer reaches EOF after first read, returning "" next time).
for i in range(1, 13):
if i < 7:
for j in range(6 - i):
print(" ", end="")
if i % 2 != 1:
print("*" * i)
else:
print("#" * i)
else:
for j in range(i - 6):
print(" ", end="")
print("*" * (12 - i))
(i)
x = 1while x < 100: x = x * 3 + 1 print(x)(ii)
for i in range(20, -1, -1): print(i)(iii)
while 899: print("*")
#
**
###
****
#####
******
*****
****
***
**
*
(i) 4 times (Values of x: 4, 13, 40, 121).
(ii) 21 times (From 20 down to 0).
(iii) Infinite times (899 is always truthy in Python).
"log.txt" containing system logs where each line may include keywords like INFO, WARNING, or ERROR. Your program should count and display how many times the word ERROR appears, then replace all occurrences of INFO with INFORMATION, and finally save the updated logs back to the same file using the with statement for safe file handling.
with open("log.txt", "r") as f:
content = f.read()
# Count ERROR occurrences
error_count = content.count("ERROR")
print("Total 'ERROR' count:", error_count)
# Replace INFO with INFORMATION
updated_content = content.replace("INFO", "INFORMATION")
# Save updated logs back to log.txt
with open("log.txt", "w") as f:
f.write(updated_content)
with open("story.txt", "w") as f:
f.write("Python is powerful. Python is easy to learn. Python is everywhere.\n")
with open("story.txt", "r") as f:
content = f.read()
words = content.split()
print("Total Words:", len(words))
new_content = content.replace("Python", "Java")
with open("updated_story.txt", "w") as f:
f.write(new_content)
print("Replacement done! Check updated_story.txt")
a) What will be the output of len(words) after the first read?b) How does split() help in counting the total number of words in the file?
c) What happens if you run the program multiple times? Will updated_story.txt always have the same content?
d) How can you modify the program to also count how many times the word ‘Python’ appeared?
a) 9 (Total 9 words present).
b) split() splits the string by whitespaces into a list of individual words, allowing len() to count total words.
c) Yes, because opening in "w" mode overwrites the file each time with the same given string.
d) Add code: python_count = content.count("Python") or iterate through list: words.count("Python").
b) Write a program in python that takes a tuple of roll numbers of students who passed the exam as an input from the user and do the following task:
(i) Take a roll number as an input from the user and check if that roll number is in the tuple.
(ii) Count how many students passed.
(iii) Print the roll numbers in ascending order.
a) Display the name of cities he visited more than 3 times.
b) Display the name of cities not having vowel in their names.
c) Display how many unique cities he visited.
a) sort() modifies the list in-place and returns None. sorted() returns a new sorted list leaving original unchanged.
# Part b
T = eval(input("Enter tuple of passed roll numbers: "))
rno = int(input("Enter roll number to search: "))
# (i)
if rno in T:
print("Roll number found!")
else:
print("Roll number not found!")
# (ii)
print("Total students passed:", len(T))
# (iii)
print("Roll numbers in ascending order:", sorted(T))
def travel(T):
# a) Visited > 3 times
print("Cities visited > 3 times:")
for city in set(T):
if T.count(city) > 3:
print(city)
# b) Cities without vowels
vowels = "aeiouAEIOU"
print("Cities without vowels:")
for city in set(T):
if not any(ch in vowels for ch in city):
print(city)
# c) Unique cities count
print("Unique cities visited:", len(set(T)))
(i) Write a function ORDER() that creates a CSV file named “orders.csv” with columns: OrderID, CustomerName, Item, Quantity, Price. Insert 8 orders into the file by taking input from the user.
(ii) Write a function DISPLAY() that reads the file “orders.csv” and display the total number of orders placed and the total revenue generated.
import csv
def ORDER():
with open("orders.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["OrderID", "CustomerName", "Item", "Quantity", "Price"])
for i in range(8):
oid = input("Enter OrderID: ")
cname = input("Enter Customer Name: ")
item = input("Enter Item: ")
qty = int(input("Enter Quantity: "))
price = float(input("Enter Price: "))
writer.writerow([oid, cname, item, qty, price])
def DISPLAY():
total_orders = 0
total_revenue = 0.0
with open("orders.csv", "r") as f:
reader = csv.reader(f)
next(reader) # skip header
for row in reader:
total_orders += 1
total_revenue += int(row[3]) * float(row[4])
print("Total Orders:", total_orders)
print("Total Revenue Generated:", total_revenue)
a) Removing duplicate words.
b) Sorting the final content alphabetically.
p1 = input("Enter paragraph 1: ")
p2 = input("Enter paragraph 2: ")
with open("file1.txt", "w") as f1:
f1.write(p1)
with open("file2.txt", "w") as f2:
f2.write(p2)
# Read both files
words = []
with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2:
words.extend(f1.read().split())
words.extend(f2.read().split())
# Remove duplicates & sort alphabetically
unique_sorted_words = sorted(list(set(words)))
# Write into merged.txt
with open("merged.txt", "w") as fm:
fm.write(" ".join(unique_sorted_words))
print("Merged file generated successfully.")
b) A company maintains a stack S to temporarily store employee records before processing them into the payroll system. Each node of the stack contains: [EmpID, Name, Salary]
Write the following functions in python:
(i) PUSH(S) – To add data of new employees given by the user and store it into the stack S repeatedly until user wants to stop it. Also displays overflow if it reaches threshold value of 500 nodes.
(ii) SHOW(S) – To display name of those employees whose salary is greater than the average salary of the company. Also print ‘Empty Stack’ if stack is empty.
b) A browser keeps a stack (History) of recently visited web pages for navigation. Each node of the stack contains: [URL, PageTitle, Timestamp]
Write the following functions in Python:
(i) DELETE(History): To delete details of recently visited page. If stack is empty then print “Under Flow”.
(ii) SHOW_RECENT(History, n): To display the last n visited pages (URL + Title). If stack is empty, print “No browsing history available”.
a) True
# (i) PUSH(S)
def PUSH(S):
while True:
if len(S) >= 500:
print("Overflow")
break
eid = input("Enter EmpID: ")
name = input("Enter Name: ")
sal = float(input("Enter Salary: "))
S.append([eid, name, sal])
choice = input("Do you want to add more? (y/n): ")
if choice.lower() != 'y':
break
# (ii) SHOW(S)
def SHOW(S):
if not S:
print("Empty Stack")
return
avg_sal = sum(emp[2] for emp in S) / len(S)
for emp in S:
if emp[2] > avg_sal:
print("Employee Name:", emp[1])
a) True
# (i) DELETE(History)
def DELETE(History):
if not History:
print("Under Flow")
else:
removed = History.pop()
print("Deleted Page:", removed)
# (ii) SHOW_RECENT(History, n)
def SHOW_RECENT(History, n):
if not History:
print("No browsing history available")
else:
for page in reversed(History[-n:]):
print("URL:", page[0], "| Title:", page[1])
b) A school stores student data in a binary file “students.dat” in the format: {“RollNo”: 1, “Name”: “John”, “Marks”: 87}
Write a Python program to:
(i) Write 50 student records to students.dat
(ii) Display Name of those students who scored more than 80 marks.
(iii) Count how many student records are present in the file.
b) A supermarket stores product details in a binary file “products.dat”. Each product is stored as: [ProductID, ProductName, Price, Stock]
Write functions to:
(i) Displays all product names that have stock less than 10 units.
(ii) Appends a new product into the same file.
(iii) Increase the price of all the products by 10 rupees whose price is more than 500.
a) Pickling: It is the process of converting Python objects (like lists, dicts) into a byte stream to save into a binary file using the pickle module.
import pickle
# (i) Write 50 student records
with open("students.dat", "wb") as f:
for i in range(1, 51):
rec = {"RollNo": i, "Name": f"Student_{i}", "Marks": 50 + i}
pickle.dump(rec, f)
# (ii) & (iii) Display >80 marks and Count
count = 0
with open("students.dat", "rb") as f:
try:
while True:
rec = pickle.load(f)
count += 1
if rec["Marks"] > 80:
print("Name:", rec["Name"])
except EOFError:
pass
print("Total student records:", count)
a) pickle.dump() method is used.
import pickle, os
# (i) Stock less than 10
def low_stock():
with open("products.dat", "rb") as f:
try:
while True:
p = pickle.load(f)
if p[3] < 10:
print("Product Name:", p[1])
except EOFError:
pass
# (ii) Append new product
def append_product():
with open("products.dat", "ab") as f:
pid = input("ID: ")
pname = input("Name: ")
price = float(input("Price: "))
stock = int(input("Stock: "))
pickle.dump([pid, pname, price, stock], f)
# (iii) Increase price by 10 if price > 500
def update_price():
fin = open("products.dat", "rb")
fout = open("temp.dat", "wb")
try:
while True:
p = pickle.load(fin)
if p[2] > 500:
p[2] += 10
pickle.dump(p, fout)
except EOFError:
fin.close()
fout.close()
os.remove("products.dat")
os.rename("temp.dat", "products.dat")
Pingback: CBSE Class 12 Computer Science Previous Year Question Papers with Solutions - Digital Study Lab