Computer Science Class 12: Python Programs That Repeat in Board Exams
Class 12 Computer Science board exams test your logic through a predictable set of recurring programming patterns. Whether you follow the CBSE, ICSE, or state board curriculum under the current academic guidelines, examiners routinely test core concepts like text file manipulation, binary file searching, CSV data processing, and stack operations using lists.
Knowing how to write these standard scripts cleanly can secure your practical and theory programming sections. Let us break down the exact categories of programs that appear year after year.
1. Text File Handling: Line-by-Line Analysis
Text file questions usually require you to read a file and filter content based on specific character patterns or word counts.
Program: Count lines not starting with 'A' or 'a'
def count_lines():
try:
with open("story.txt", "r") as file:
count = 0
for line in file:
# Strip leading whitespaces to check the first character accurately
stripped_line = line.lstrip()
if stripped_line and not stripped_line.startswith(('A', 'a')):
count += 1
print(f"Total lines not starting with A/a: {count}")
except FileNotFoundError:
print("The file story.txt does not exist.")
count_lines()
Common variations of this question ask you to count vowels, count specific words like "the", or display words with fewer than four letters. Always remember to use with open(...) as it automatically handles closing the file resource.
2. Binary File Handling: Pickle Module Operations
Binary files use the pickle module (pickle.dump() and pickle.load()). Examiners favor questions where you append records to a binary file and then search or update them based on a unique ID or roll number.
Program: Search for a record in a binary file
import pickle
def search_student(roll_no):
found = False
try:
with open("student.dat", "rb") as file:
while True:
try:
record = pickle.load(file)
if record['RollNo'] == roll_no:
print("Record Found:")
print(f"Name: {record['Name']}, Marks: {record['Marks']}")
found = True
break
except EOFError:
break
if not found:
print("Student record not found.")
except FileNotFoundError:
print("Binary file not found.")
# Example usage
# search_student(15)
Make sure you wrap your pickle.load() inside a while True loop terminated by an EOFError exception. Missing this structure is a common reason students lose marks.
3. CSV File Processing: Using the csv Module
With data-driven questions becoming standard across boards, CSV file handling is a high-yield topic. You must know how to import the csv module and use csv.reader or csv.writer.
Program: Read and display employee records earning above a threshold
import csv
def high_ earners():
try:
with open("emp.csv", "r", newline="") as file:
reader = csv.reader(file)
header = next(reader) # Skip header row
print(header)
for row in reader:
# Assuming salary is at index 2 (converted to float)
if float(row[2]) > 50000:
print(row)
except FileNotFoundError:
print("CSV file missing.")
high_earners()
4. Stack Operations Using Lists
Linear data structures—specifically the Stack (LIFO: Last In, First Out)—are compulsory in board papers. You must implement push and pop operations using Python lists, handling underflow conditions correctly.
Program: Push and Pop for a book database stack
def push_book(stack, book_name):
stack.append(book_name)
print(f"Pushed: {book_name}")
def pop_book(stack):
if len(stack) == 0:
print("Underflow! Stack is empty.")
return None
else:
removed = stack.pop()
print(f"Popped: {removed}")
return removed
def display_stack(stack):
if not stack:
print("Stack is empty.")
else:
# Display from top to bottom
print("Stack (Top to Bottom):")
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
# Driver code
books_stack = []
push_book(books_stack, "Python Basics")
push_book(books_stack, "Data Structures")
pop_book(books_stack)
display_stack(books_stack)
Comparison of File Types in Board Exams
| File Type | Module Needed | Key Functions / Methods | Common Pitfall |
| :--- | :--- | :--- | :--- |
| Text File (.txt) | Built-in | read(), readline(), readlines(), write() | Forgetting to add newline characters \n when writing. |
| Binary File (.dat) | pickle | pickle.dump(), pickle.load() | Forgetting the EOFError exception handler during reading. |
| CSV File (.csv) | csv | csv.reader(), csv.writer(), next() | Forgetting newline="" in open(), causing blank rows. |
Quick Checklist for Your Exam
- [ ] Did you import all required modules (
pickle,csv,math, etc.) at the top of your script? - [ ] Are all file operations enclosed within
try-exceptblocks to handleFileNotFoundError? - [ ] Did you close your files properly, or even better, use the
withcontext manager? - [ ] For stacks, did you check for
Underflowbefore running a pop operation? - [ ] Are your variable names logical and indentation uniform (4 spaces)?
