Edumath by Sereddy logo

Computer Science Class 12: Python Programs That Repeat in Exams

21 August 2026 · Yesunadhareddy SereddyClass 12 CSPython ProgramsCBSE Board ExamsEdumath

Scoring a 90+ in CBSE Class 12 Computer Science depends heavily on your practical coding section. While concepts like SQL and networking test your theory, the Python programming section tests your logical precision. Examiners repeat specific categories of programs every year because they test fundamental computational thinking: file handling, data structures, and user-defined functions.

Here is a breakdown of the core Python program patterns that frequently appear in Class 12 board exams, complete with standard structures you can adapt directly on your answer sheet.

1. Text File Operations: Counting and Searching

File handling questions carry heavy weightage in the practical and theory papers. The most common pattern asks you to read a text file and perform conditional string checks.

Example: Count specific words or lines

You will often be asked to count words starting with a specific letter, count total vowels, or count lines not starting with a particular character.

def count_target_words(filename):
    count = 0
    try:
        with open(filename, "r") as file:
            for line in file:
                words = line.split()
                for word in words:
                    # Check if word starts with 'A' or 'a'
                    if word[0].lower() == "a":
                        count += 1
        print(f"Total words starting with A/a: {count}")
    except FileNotFoundError:
        print("File not found.")

Exam Tip: Always use the with open() context manager. It automatically closes the file, preventing loss of marks for resource management. Always include a try-except block for safety.

2. Binary File Operations: Using pickle

Binary files require serialization using the pickle module. Board questions in this category generally test your ability to append records (dictionaries or lists) and search or update them.

Example: Writing and reading student records

Expect a 3-mark or 4-mark question where you must store roll numbers, names, and marks, then search for a specific roll number.

import pickle


def write_record():
    with open("student.dat", "ab") as f:
        roll = int(input("Enter Roll No: "))
        name = input("Enter Name: ")
        marks = float(input("Enter Marks: "))
        record = [roll, name, marks]
        pickle.dump(record, f)


def search_student(r_id):
    found = False
    try:
        with open("student.dat", "rb") as f:
            while True:
                record = pickle.load(f)
                if record[0] == r_id:
                    print(f"Found! Name: {record[1]}, Marks: {record[2]}")
                    found = True
                    break
    except EOFError:
        pass
    if not found:
        print("Record not found.")

Common Mistake: Forgetting to handle the EOFError when reading a binary file using an infinite while True: loop. Without try...except EOFError:, your program crashes at the end of the file.

3. CSV File Operations: Importing csv

Questions on Comma Separated Values (CSV) files test basic tabular data handling using Python's built-in csv module.

Example: Writing and reading CSV rows

import csv


def write_csv():
    with open("emp.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["EmpID", "Name", "Salary"])  # Header
        writer.writerow([101, "Aarav", 50000])
        writer.writerow([102, "Diya", 65000])


def read_csv():
    with open("emp.csv", "r") as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)

Exam Tip: Do not forget the newline='' parameter in open(). Omitting it can result in blank extra lines between rows on Windows systems during evaluation.

4. Stack Implementation Using Lists

Data structures—specifically Stacks implemented using Python lists—are a permanent fixture in the Class 12 board paper. You must know how to handle push, pop, and display operations.

Example: Push and Pop operations for a Book library

def push_book(stack, book_name):
    stack.append(book_name)
    print(f"Book '{book_name}' pushed successfully.")


def pop_book(stack):
    if len(stack) == 0:
        print("Stack Underflow! No books to remove.")
    else:
        item = stack.pop()
        print(f"Popped book: {item}")


def display_stack(stack):
    if len(stack) == 0:
        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])

Quick Checklist for Python Coding Questions

Use this checklist during your revision to ensure you don't lose marks to silly syntax errors:

| Component | What to Verify | | :--- | :--- | | Indentation | Strictly use 4 spaces consistently; mixed tabs and spaces cause IndentationError. | | File Modes | Use "r" for reading, "w" for writing, "a" for appending, and add "b" for binary files ("rb", "wb"). | | Modules | Ensure required modules like pickle, csv, or math are explicitly imported at the top of your code snippet. | | Loop Termination | In binary file searches, always wrap pickle.load() inside a try-except EOFError block. |

Practicing these exact patterns repeatedly builds muscle memory, allowing you to finish the coding section with time to spare for dry-running your logic before final submission.