CBSE Class 12 Computer Science Mid Term Question Paper 2025-26 with Solutions (Morning Shift)

CBSE Class 12 Computer Science Mid Term Question Paper 2025-26 with Solutions (Morning Shift)
SECTION A
CBSE Class 12 Computer Science Mid Term Question Paper 2025-26 Solutions
CBSE Mid-Term Question Paper Solutions (Section B to E)
SECTION B
Question 22 2 Marks
Write a python program that read the data from a CSV file named "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
šŸ’” Solution:
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")
Question 23 2 Marks
Write a function HURRY() in python that reads the content of a text file "abc.txt" and print one word randomly from each line.
── OR ──
Write a function 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.
šŸ’” Solution (Main):
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))
šŸ’” Solution (OR):
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)
Question 24 2 Marks
Rewrite the following code after removing errors (Underline the changes) to print only those numbers that are multiple of 7 and 5 in reverse order from N to 1 (including N and 1) where value of N should be given by the user.
N=int(input("Give a number"))
a=1
while N>a:
    if N%5==0 or N%7==0:
        print(a, end=" ")
    N+=1
šŸ’” Corrected Code:
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
Question 25 2 Marks
Write a function MULTIPLE(data, n) that prints all keys of data whose values are multiples of n. Here, data is a dictionary.
── OR ──
Write a function 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.
šŸ’” Solution (Main):
def MULTIPLE(data, n):
    for key, value in data.items():
        if value % n == 0:
            print(key)
šŸ’” Solution (OR):
def FUN(N, A):
    L = []
    for i in range(1, N + 1):
        if i % A != 0:
            L.append(i)
    return L
Question 26 2 Marks
A CSV file is showing semicolons instead of commas as separators. Can it still be read in Python? How?
── OR ──
Your teacher asked you to share marks in a way that can be opened in Excel. Which file type would you choose and why?
šŸ’” Solution (Main):

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)
šŸ’” Solution (OR):

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.

Question 27 2 Marks
Fill in the blanks:
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.
šŸ’” Answers:

a) False

b) and

Question 28 2 Marks
A shopping cart application tries to convert user input into an integer for quantity. If the user enters 2 (type string) then it converts it into 2 (type integer) but if user enters a text like “two” instead of 2, the program crashes with ValueError.

Write a program in python to handle this using try-except so the user is asked to re-enter a valid number?
šŸ’” Solution:
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.")
SECTION C
Question 29 3 Marks
State True or False:
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.
šŸ’” Answers:

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).

Question 30 3 Marks
Predict the output of the following python program:
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))
── OR ──
How many times the following loop will iterate?
(i) x = 1
while x < 100:
    x = x * 3 + 1
    print(x)

(ii) for i in range(20, -1, -1):
    print(i)

(iii) while 899:
    print("*")
šŸ’” Output (Main):
     #
    **
   ###
  ****
 #####
******
 *****
  ****
   ***
    **
     *
     
šŸ’” Solution (OR):

(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).

Question 31 3 Marks
Write a program in python to analyze a log file "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.
šŸ’” Solution:
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)
SECTION D
Question 32 4 Marks
Read the following python program and answer the questions:
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?
šŸ’” Answers:

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").

Question 33 4 Marks
a) Differentiate between sort() and sorted() functions of list.
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.
── OR ──
A tuple T stores city names visited by a traveller (some may repeat). Write a function travel() in python that performs the following tasks:
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.
šŸ’” Solution (Main):

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))
šŸ’” Solution (OR):
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)))
Question 34 4 Marks
An e-commerce website maintains its order details in a CSV file.

(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.
šŸ’” Solution:
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)
Question 35 4 Marks
Create two text files, “file1.txt” and “file2.txt”. Take two paragraphs in the form of string as an input from the user and store one in “file1.txt” and other in “file2.txt”. Now each file containing few words (some may repeat). Write a program in python that merges both files into a single file “merged.txt”. Perform the following tasks on “merged.txt”:
a) Removing duplicate words.
b) Sorting the final content alphabetically.
šŸ’” Solution:
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.")
SECTION E
Question 36 5 Marks
a) Top value of the stack (implemented using list) stores at index -1. (True/False)
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.
── OR ──
a) Stacks are used in undo/redo operations in applications. (True/False)
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”.
šŸ’” Solution (Main):

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])
šŸ’” Solution (OR):

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])
Question 37 5 Marks
a) What is pickling?
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.
── OR ──
a) Which method is used to serialize an object into a binary 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.
šŸ’” Solution (Main):

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)
šŸ’” Solution (OR):

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")

1 thought on “CBSE Class 12 Computer Science Mid Term Question Paper 2025-26 with Solutions (Morning Shift)”

  1. Pingback: CBSE Class 12 Computer Science Previous Year Question Papers with Solutions - Digital Study Lab

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top