Edumath by Sereddy logo

Study Blog

Daily tips & exam updates

Computer Science Class 12: Python programs that repeat in exams

26 October 2026 · Yesunadhareddy SereddyClass 12 CSPython ProgramsCBSE Board ExamsEdumath

Computer Science Class 12 board exams test your ability to implement core logic using Python. While output-based questions and theoretical definitions carry substantial weight, writing code segments—specifically involving text files, binary files, CSV files, stacks, and user-defined functions—forms the backbone of the subjective section.

This guide breaks down the Python programs that repeatedly feature across CBSE Class 12 board papers, sample papers, and pre-board examinations under the current curriculum.

File Handling: Text and Binary Files

File handling questions consistently appear in the 3-mark and 4-mark categories. Examiners look for proper file opening modes, error prevention, and clean looping logic.

1. Reading and Counting Specific Characters or Words

A classic question requires reading a text file line by line and filtering words based on starting letters or specific substrings.

def count_words():
    file = open("story.txt", "r")
    count = 0
    data = file.read()
    words = data.split()
    for w in words:
        if w[0].lower() == 'a' or w[0].lower() == 'e':
            count += 1
    print("Words starting with A or E:", count)
    file.close()

2. Binary File Operations using pickle

Binary file questions test your understanding of serializing and deserializing complex data structures like dictionaries or lists using the pickle module.

import pickle

def write_binary():
    f = open("student.dat", "wb")
    while True:
        roll = int(input("Enter Roll No: "))
        name = input("Enter Name: ")
        marks = float(input("Enter Marks: "))
        rec = [roll, name, marks]
        pickle.dump(rec, f)
        ch = input("Add more? (y/n): ")
        if ch.lower() == 'n':
            break
    f.close()

def search_student(rno):
    f = open("student.dat", "rb")
    found = False
    try:
        while True:
            data = pickle.load(f)
            if data[0] == rno:
                print("Record Found:", data[1], "Marks:", data[2])
                found = True
    except EOFError:
        pass
    finally:
        f.close()
    if not found:
        print("Roll number not found.")

Data Structures: Implementing Stacks in Python

The stack is the only data structure explicitly mandated in the Class 12 CS syllabus. You will almost certainly encounter a question requiring you to push, pop, or display records (often implemented using a Python list).

3. Stack Implementation for Dictionary Records

Examiners prefer questions where elements added to the stack are tuples or dictionaries, such as book IDs and book titles.

def push_book(stk, book):
    stk.append(book)
    print(f"Book '{book[1]}' pushed successfully.")

def pop_book(stk):
    if len(stk) == 0:
        print("Stack Underflow! No books to remove.")
    else:
        item = stk.pop()
        print(f"Removed Book ID: {item[0]}, Title: {item[1]}")

def display_stack(stk):
    if len(stk) == 0:
        print("Stack is empty.")
    else:
        print("Stack elements (Top to Bottom):")
        for i in range(len(stk)-1, -1, -1):
            print(stk[i])

# Execution structure
stack = []
push_book(stack, (101, "Python Programming"))
push_book(stack, (102, "Data Structures"))
display_stack(stack)
pop_book(stack)

Database Connectivity with MySQL and Python

To bridge Python and SQL, board papers frequently ask for a script that executes a query, fetches rows, and handles parameters safely.

4. Fetching Records with Conditions

import mysql.connector as sql

def get_toppers():
    conn = sql.connect(
        host="localhost",
        user="root",
        password="your_password",
        database="school"
    )
    cursor = conn.cursor()
    cursor.execute("SELECT Name, Marks FROM students WHERE Marks > 90")
    records = cursor.fetchall()
    
    print("--- Toppers List ---")
    for row in records:
        print(f"Name: {row[0]} | Marks: {row[1]}")
        
    cursor.close()
    conn.close()

Common Board Question Patterns

To score full marks, pay attention to minor syntactic details that evaluators check. The table below outlines common error points in repeating programming questions:

| Concept | Common Student Error | Correct Approach | | :--- | :--- | :--- | | Text Files | Forgetting to use .close() or .split() | Always close files or use with open(...) as f: syntax. | | Binary Files | Missing EOFError handling during pickle.load() | Always enclose pickle.load() inside a try...except EOFError block. | | Stacks | Confusing queue operations (FIFO) with stack operations (LIFO) | Ensure insertion and deletion happen at the same end using .append() and .pop(). | | MySQL Connectivity | Forgetting to import mysql.connector or missing cursor execution | Instantiate the cursor using conn.cursor() before running .execute(). |

Quick Checklist for Exam Day

  • [ ] Always write comments if specified, but focus primarily on clean, indented logic.
  • [ ] For file handling, verify whether the file mode requires reading ("r", "rb"), writing ("w", "wb"), or appending ("a").
  • [ ] When returning values from user-defined functions in stacks or queues, ensure edge cases like empty structures are explicitly checked.
  • [ ] Double-check variable names across function definitions and main code blocks. A single typo results in a NameError and loss of marks.

Practicing these template programs repeatedly ensures you finish your practical coding section well within the allotted exam time. Keep coding, stay consistent, and master every concept with Edumath!