Computer Science Class 12: Python Programs That Repeat in Exams
In CBSE Class 12 Computer Science, the coding section separates a 70/70 scorer from the rest. While output-based questions test your dry-running skills, writing Python programs from scratch requires a firm grip on syntax and fundamental logic. Based on board exam trends, certain programming patterns appear year after year with minor tweaks in data values or problem statements.
This guide breaks down the core Python program categories that consistently show up in theory papers and practical exams under the 2026-27 curriculum, complete with implementation logic and common student pitfalls.
1. Binary File Operations using pickle
Working with binary files is non-negotiable for Section D of the CBSE paper. Questions usually ask you to create, read, search, or update records stored in a binary file using Python's built-in pickle module.
Common Variations
- Append/Write Records: Taking user input (Roll Number, Name, Marks) and dumping dictionaries or lists into a
.datfile. - Read/Search Records: Traversing the file using
pickle.load()inside atry-exceptblock withEOFErrorto find a specific roll number or condition (e.g., marks ). - Update Records: Reading the entire file into a list, modifying the target record in memory, and overwriting the file.
Boilerplate Search Pattern
import pickle
def search_student():
found = False
try:
with open("student.dat", "rb") as file:
while True:
data = pickle.load(file)
if data["Marks"] > 90:
print(data["Name"], data["Marks"])
found = True
except EOFError:
pass
if not found:
print("No matching record found.")
Examiner Tip: Always wrap your file reading loops inside a try-except block handling EOFError. Missing this causes your code to crash during evaluation when it hits the end of the file.
2. Text File Parsing and Character Counting
Text file manipulation tests string handling combined with file handling commands like read(), readline(), and readlines().
Frequent Questions
- Count lines starting with a specific alphabet (e.g., 'A' or 'M').
- Count the total number of lowercase, uppercase, vowels, or specific words (like "the" or "this") in a text file.
- Copy lines from one file to another, omitting lines containing a specific keyword.
Essential String Checking Logic
| Task | Python Implementation Snippet |
| :--- | :--- |
| Count lines starting with 'S' | if line.startswith('S') or line.startswith('s'): |
| Count word frequency | words = line.split(); count += words.count("to") |
| Check for specific substring | if "CBSE" in line: |
3. Stack Implementation using Lists (LIFO)
Data Structures questions invariably feature stacks implemented via Python lists. You are expected to write functions for Push and Pop, often handling a list of dictionaries containing employee or book details.
Standard Template
def Push(stack, item):
stack.append(item)
def Pop(stack):
if len(stack) == 0:
return "Underflow"
else:
return stack.pop()
When dealing with dictionaries (e.g., pushing [Book_No, Book_Name]), ensure you manage the top-of-stack pointer or list length accurately. Watch out for questions that ask you to display elements from the top of the stack downwards without using built-in reversal methods.
4. User-Defined Functions with Default Arguments and Return Values
Modular programming questions require writing a function that accepts a list, string, or tuple, manipulates it, and returns the modified data structure.
Repeated Logic Patterns
- List Manipulation: Interchange elements of adjacent indices (e.g., swap index 0 with 1, 2 with 3). If the length is odd, the last element remains untouched.
- String Manipulation: Replace all vowels with a specific symbol or reverse words in a sentence while keeping their positions intact.
Example: Swapping Even-Indexed Elements with Odd-Indexed Elements
val = [10, 20, 30, 40, 50] # Output should handle odd lengths safely
def swap_alt(arr):
n = len(arr)
for i in range(0, n - 1, 2):
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
Quick Checklist for Class 12 CS Coding
- [ ] Did you import all required modules (
pickle,csv,mathetc.)? - [ ] Are your file paths correct and closed properly (or handled using the
withstatement)? - [ ] Did you handle the
EOFErrorexception while reading binary files? - [ ] Are your list indices within bounds to prevent
IndexErrorduring string or array traversals? - [ ] Have you indented your code blocks consistently (4 spaces per level)?
Practice these four core areas extensively using past board papers. Writing clean code with proper variable naming not only fetches full marks but also saves time for debugging during the exam.
