Edumath by Sereddy logo

Study Blog

Daily tips & exam updates

Computer Science Class 12: Python Programs That Repeat in Exams

20 October 2026 · Yesunadhareddy SereddyComputer SciencePythonCBSE Class 12Board Exams

Cracking the Class 12 Python Coding Section

Python programming questions carry significant weight in the Class 12 Computer Science board examinations under the CBSE, ICSE, and various state boards following the NCF-SE framework. Examiners repeatedly test specific logical patterns across text files, binary files, CSV files, and linear data structures. Memorizing syntax will not help here; understanding the underlying logic is essential.

This guide breaks down the core Python programming archetypes that appear year after year, complete with clean code snippets aligned with the latest curriculum.


1. Text File Handling: The Counting Patterns

Text file questions almost always involve reading a file line by line or character by character to perform conditional counting or string manipulation.

Program: Count Vowels, Consonants, Uppercase, and Lowercase Letters

def count_file_details(filename):
    vowels = "aeiouAEIOU"
    v_count = c_count = u_count = l_count = 0

    try:
        with open(filename, "r") as file:
            data = file.read()
            for char in data:
                if char.isalpha():
                    if char in vowels:
                        v_count += 1
                    else:
                    c_count += 1

                    if char.isupper():
                        u_count += 1
                    elif char.islower():
                        l_count += 1

        print(f"Vowels: {v_count}")
        print(f"Consonants: {c_count}")
        print(f"Uppercase: {u_count}")
        print(f"Lowercase: {l_count}")

    except FileNotFoundError:
        print("The specified file does not exist.")


# Example usage:
# count_file_details("story.txt")

Common Variations in Exams

  • Displaying only those lines that start with a specific alphabet (e.g., 'A' or 'M').
  • Replacing a specific word (e.g., replacing "this" with "that") throughout the text file.
  • Finding the longest word in the text file.

2. Binary Files: Pickling and Unpickling

Binary file handling using the pickle module is a high-yield topic. Questions typically ask you to write records (using dictionaries or lists) into a binary file, search for a specific record by roll number or ID, and display it.

Program: Add and Search Records in a Binary File

import pickle


def write_student():
    with open("student.dat", "wb") as f:
        while True:
            try:
                roll = int(input("Enter Roll No: "))
                name = input("Enter Name: ")
                marks = float(input("Enter Marks: "))
                record = {"Roll": roll, "Name": name, "Marks": 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(target_roll):
    found = False
    try:
        with open("student.dat", "rb") as f:
            while True:
                try:
                    record = pickle.load(f)
                    if record["Roll"] == target_roll:
                        print(f"Found! 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.")

3. CSV Files: Using the csv Module

With the integration of data-handling competencies, questions on reading and writing comma-separated values using Python's built-in csv module are standard.

Program: Writing and Reading CSV Employee Records

import csv


def write_csv():
    with open("emp.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["EmpID", "Name", "Department"])
        writer.writerow([101, "Aarav", "IT"])
        writer.writerow([102, "Diya", "HR"])


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

4. Stack Operations using Lists

The stack is the primary data structure tested in Class 12 Computer Science. Because lists in Python allow dynamic sizing, implementing a stack requires managing the top pointer.

Program: Push, Pop, and Display a Stack of Books

def is_empty(st):
    return len(st) == 0


def push(st, item):
    st.append(item)
    print(f"Pushed: {item}")


def pop(st):
    if is_empty(st):
        return "Underflow"
    return st.pop()


def display(st):
    if is_empty(st):
        print("Stack is empty")
    else:
        # Display from top to bottom
        for i in range(len(st) - 1, -1, -1):
            print(f"| {st[i]} |")
        print("---")


# Example execution
stack = []
push(stack, "Python Guide")
push(stack, "Physics NCERT")
push(stack, "Maths Calculus")
display(stack)
print("Popped:", pop(stack))
display(stack)

File Handling Error Quick Reference

| Mode | Operation | File Exists? | Action / Behavior | | :--- | :--- | :--- | :--- | | 'r' | Read | No | Raises FileNotFoundError | | 'w' | Write | Yes / No | Overwrites existing file or creates new | | 'a' | Append | Yes / No | Appends to end of file or creates new | | 'rb' | Read Binary | No | Raises FileNotFoundError | | 'wb' | Write Binary| Yes / No | Overwrites existing binary file |


Quick Checklist for Exam Day

  • Imports: Never forget to import required modules like pickle or csv.
  • File Closing: Always use with open(...) context managers to automatically handle file closures, or explicitly call .close() inside a try...finally block.
  • EOF Handling: When reading binary files with pickle.load(), always wrap the read operation inside a while True loop and catch the EOFError.
  • Newline Parameter: When writing CSV files on Windows, always specify newline='' in open() to prevent blank rows between entries.
  • Indentation & Colon: Double-check indentation inside loops and verify that every if, def, while, and for statement ends with a colon (::).