Computer Science Class 12: Python Programs That Repeat in Exams
Board exams for CBSE Class 12 Computer Science test a predictable set of programming patterns every single year. While the context changes—sometimes it is about books, sometimes about students, employees, or temperatures—the underlying logic required to solve the question remains identical.
Scoring full marks in the programming sections requires recognizing these core patterns instantly. This guide breaks down the high-frequency Python programs you must master, focusing on text files, binary files, CSV files, and Data Structures.
1. Text File Manipulation: Counting and Filtering
Text file questions in the board exam usually ask you to read a file line by line or character by character, perform a conditional check, and display or count specific elements.
Frequently Asked Pattern: Case and Character Counting
You are often given a file named story.txt and asked to count uppercase letters, lowercase letters, specific vowels, or words starting with a particular letter.
def count_up_low(filename):
up = 0
low = 0
try:
with open(filename, 'r') as file:
data = file.read()
for char in data:
if char.isupper():
up += 1
elif char.islower():
low += 1
print(f"Uppercase characters: {up}")
print(f"Lowercase characters: {low}")
except FileNotFoundError:
print("Error: File not found.")
Frequently Asked Pattern: Replacing or Displaying Specific Words
Another classic question asks you to read lines and display only those words that meet a length criterion, or replace a specific word like "the" with "THE".
def display_short_words(filename):
with open(filename, 'r') as file:
lines = file.readlines()
for line in lines:
words = line.split()
for w in words:
if len(w) < 4:
print(w, end=' ')
print()
2. Binary Files: The pickle Module
Binary file operations using the built-in pickle module are compulsory in the board question paper. You will almost always see a question asking you to either append a dictionary/list to a binary file or search through a binary file using a specific record ID or roll number.
Frequently Asked Pattern: Writing and Reading Records
Here is how board questions test your understanding of pickle.dump() and pickle.load() inside a loop using EOFError.
import pickle
def write_student():
with open("student.dat", "wb") as f:
while True:
try:
rno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
record = [rno, name, marks]
pickle.dump(record, f)
choice = input("Add more? (y/n): ")
if choice.lower() != 'y':
break
except ValueError:
print("Invalid input format.")
def search_student(rno_to_search):
found = False
try:
with open("student.dat", "rb") as f:
while True:
record = pickle.load(f)
if record[0] == rno_to_search:
print(f"Record Found: Name: {record[1]}, Marks: {record[2]}")
found = True
break
except EOFError:
if not found:
print("Student record not found in file.")
except FileNotFoundError:
print("Data file does not exist yet.")
3. CSV Files: Using the csv Module
With the integration of data modules in the curriculum, CSV file handling has become a regular feature. Questions typically require using csv.reader() or csv.writer().
Frequently Asked Pattern: Searching CSV Rows
import csv
def search_employee(emp_id):
found = False
try:
with open("emp.csv", "r", newline='') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
if row and row[0] == str(emp_id):
print(f"Employee Details: {row}")
found = True
break
if not found:
print("Employee ID not found.")
except FileNotFoundError:
print("CSV file missing.")
4. Data Structures: Stack Implementation
Questions on stacks using lists in Python test your ability to maintain a proper pointer (Top) and handle underflow and overflow conditions correctly.
Frequently Asked Pattern: Push and Pop Operations with Dictionaries
Board exams often complicate standard stack questions by asking you to push records (like Book ID and Book Title) where the Book ID is even or odd.
def push_book(stack, book):
stack.append(book)
top = len(stack) - 1
def pop_book(stack):
if len(stack) == 0:
print("Stack Underflow!")
return None
else:
return stack.pop()
def display_stack(stack):
if len(stack) == 0:
print("Stack is empty.")
else:
top = len(stack) - 1
print(f"Top -> {stack[top]}")
for i in range(top - 1, -1, -1):
print(stack[i])
Comparison of File Modes in Python
To avoid silly syntax errors during exam coding, review the required modes for different file types:
| File Type | Read Mode | Write Mode (Overwrite) | Append Mode |
| :--- | :--- | :--- | :--- |
| Text File | 'r' | 'w' | 'a' |
| Binary File | 'rb' | 'wb' | 'ab' |
| CSV File | 'r' (with newline='') | 'w' (with newline='') | 'a' (with newline='') |
Quick Checklist for Exam Success
- [ ] Always import necessary modules (
pickle,csv) at the very top of your script. - [ ] Wrap file operations inside
try...exceptblocks to prevent runtime crashes during evaluation. - [ ] Always use
with open(...)context managers to automatically handle file closing. - [ ] For binary files, remember to catch the
EOFErrorwhen reading using awhile Trueloop. - [ ] Check for
Stack Underflowbefore executing apop()operation in lists.
