Edumath by Sereddy logo

Computer Science Class 12: Python Programs That Repeat in Exams

8 September 2026 · Yesunadhareddy SereddyComputer SciencePythonClass 12CBSE

Cracking the Class 12 CS Practical and Theory Papers

Scoring a full hundred in Class 12 Computer Science (CBSE, ICSE, or State Boards) hinges heavily on your programming section. Examiners love patterns. Year after year, specific logic types—ranging from text file manipulation to stack operations—reappear in section-based descriptive questions.

This guide breaks down the high-frequency Python programs you must practice until your fingers memorize the syntax. We focus on core modules aligned with the current curriculum: Text Files, Binary Files, Stacks, and CSV handling.

1. Text File Handling: Counting and Filtering

File handling questions carry heavy weight in both theory and practical exams. The most common pattern asks you to read a text file line by line or character by character and apply a conditional check.

Problem: Count Vowels or Specific Words

Write a function count_lower_vowels() that reads a text file named note.txt and counts how many lowercase vowels are present in it.

def count_lower_vowels():
    file = open("note.txt", "r")
    data = file.read()
    count = 0
    vowels = "aeiou"
    
    for char in data:
        if char in vowels:
            count += 1
            
    print("Total lowercase vowels:", count)
    file.close()

Examiner's Trap: Students often forget to close the file or fail to handle FileNotFoundError. Using a with statement is safer and earns full style points:

def count_lower_vowels_safe():
    try:
        with open("note.txt", "r") as file:
            count = sum(1 for char in file.read() if char in "aeiou")
            print("Total lowercase vowels:", count)
    except FileNotFoundError:
        print("File not found.")

2. Binary Files: Pickle Module Operations

Questions involving pickle.dump() and pickle.load() are mandatory in every set of the board paper. They usually test your ability to append records (dictionaries or lists) to a binary file and search through them.

Problem: Searching a Record by Roll Number

Assume a binary file student.dat stores records as dictionaries: {"roll": int, "name": str, "marks": float}. Write a function to search for a given roll number and display the student's name.

import pickle

def search_student(rno):
    found = False
    try:
        with open("student.dat", "rb") as f:
            while True:
                record = pickle.load(f)
                if record["roll"] == rno:
                    print("Name:", record["name"])
                    found = True
                    break
    except EOFError:
        pass
    
    if not found:
        print("Record not found.")

Crucial Rule: Always wrap pickle.load(f) inside a while True: loop accompanied by a try-except EOFError: block. Missing the EOFError handling loses you direct marks.

3. Data Structures: Implementing a Stack in Lists

Stacks operate on the Last In, First Out (LIFO) principle. In Python, we implement stacks using lists with .append() for PUSH and .pop() for POP. Board questions frequently ask you to push and pop records containing customer names or book titles based on a specific condition (e.g., length of string).

Problem: Push and Pop Operations for Book Titles

Write functions Push_Book(Stack, book) and Pop_Book(Stack) to manage a stack of books where the book title starts with 'A'.

def Push_Book(Stack, book):
    Stack.append(book)

def Pop_Book(Stack):
    if len(Stack) == 0:
        return "Underflow"
    else:
        return Stack.pop()

Sometimes examiners ask you to process a complete list into a stack function:

def transfer_books(BookList):
    stack = []
    for book in BookList:
        if book.startswith('A') or book.startswith('a'):
            Push_Book(stack, book)
            
    while len(stack) > 0:
        print("Popped:", Pop_Book(stack))

4. CSV Files: Reading and Writing

With the inclusion of the csv module in the syllabus, questions requiring reading and writing comma-separated values using csv.writer and csv.reader are standard.

Problem: Writing Student Records to a CSV File

import csv

def write_csv():
    with open("student.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Roll", "Name", "Percentage"])
        writer.writerow([1, "Aarav", 92.5])
        writer.writerow([2, "Diya", 88.0])

| Function Module | Core Operation | Common Error to Avoid | | :--- | :--- | :--- | | pickle | Binary serialization | Forgetting rb or wb file modes | | csv | Tabular text parsing | Forgetting newline="" in open() | | text file | String processing | Assuming lines include explicit newlines \n during iteration |

Quick Checklist

  • [ ] Practiced writing try...except EOFError loops for binary files without hesitation.
  • [ ] Remembered that stack.pop() on an empty list throws an IndexError, so underflow checks are mandatory.
  • [ ] Verified file opening modes: "r" for read, "w" for write, "a" for append, and adding "b" for binary files.
  • [ ] Practiced importing required standard libraries (pickle, csv, math) at the top of code snippets.

Head over to Edumath by sereddy for more chapter-wise problem sets, solved past-year board questions, and targeted revision sheets for your Class 12 exams.