Edumath by Sereddy logo

Computer Science Class 12: Python Programs That Repeatedly Appear in CBSE Board Exams

15 August 2026 · Yesunadhareddy SereddyClass 12 Computer SciencePythonCBSE Board ExamsEdumath

In the Class 12 Computer Science practical and theory papers, examiners test your logical problem-solving through specific Python constructs. While the syllabus covers advanced topics, certain programming patterns appear year after year with minor variations in data or wording. Scoring full marks in the coding section requires absolute mastery of these recurring templates.

File Handling: The Most Predictable 4-Mark Question

Text and binary file handling questions appear in almost every board paper. Examiners frequently test your ability to read data, search for specific records, and update files.

Searching and Displaying Records

A classic question requires you to read a text file (like notes.txt) and count specific words, characters, or lines, or read a binary file using the pickle module to search for a specific record by roll number or ID.

import pickle


def search_student():
    try:
        with open("student.dat", "rb") as file:
            rno = int(input("Enter Roll Number to search: "))
            found = False
            while True:
                data = pickle.load(file)
                if data["RollNo"] == rno:
                    print(
                        f"Found! Name: {data['Name']}, Marks: {data['Marks']}"
                    )
                    found = True
                    break
    except EOFError:
        if not found:
            print("Record not found in the file.")
    except FileNotFoundError:
        print("File does not exist.")


search_student()

When writing file handling code in exams, always wrap your reading logic in a try-except block, specifically catching EOFError when reading binary files using pickle.load() inside a while True loop. Missing this results in direct mark deductions.

Stack Implementation Using Lists

Data structures form a high-weightage section in the CBSE Class 12 curriculum. Implementing a Stack using a Python list is a staple 3 or 4-mark question.

Push and Pop Operations

You will often be asked to write functions to insert elements (Push), delete elements (Pop), and display the stack.

def isEmpty(stk):
    if stk == []:
        return True
    else:
        return False


def Push(stk, item):
    stk.append(item)
    print(f"Inserted: {item}")


def Pop(stk):
    if isEmpty(stk):
        print("Stack Underflow!")
    else:
        item = stk.pop()
        print(f"Popped: {item}")


# Driver code example
stack = []
Push(stack, 10)
Push(stack, 20)
Pop(stack)

Examiners look for proper handling of Stack Underflow (popping from an empty stack) and clarity in maintaining the top-most element.

Database Connectivity with MySQL and Python

Integrating Python with MySQL using the mysql.connector module is a guaranteed question in the 30-mark practical examination and frequently appears as a case-based or direct query question in the theory paper.

Inserting and Fetching Records

You must know how to establish a connection, create a cursor, execute queries, and commit changes for insert operations.

import mysql.connector


def get_toppers():
    try:
        conn = mysql.connector.connect(
            host="localhost", user="root", password="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]}")

    except mysql.connector.Error as err:
        print(f"Error: {err}")
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()


get_toppers()

| Operation Method | Purpose | Important Rule | | :--- | :--- | :--- | | cursor.execute(query) | Runs the SQL query | Use parameterized queries for user inputs to prevent errors. | | cursor.fetchall() | Fetches all rows from the result set | Returns a tuple of tuples; iterate using standard loops. | | conn.commit() | Saves changes permanently | Mandatory for INSERT, UPDATE, and DELETE queries. |

User-Defined Functions: String and List Manipulation

Questions testing basic algorithmic thinking involve manipulating strings or lists without using built-in shortcuts. Common tasks include replacing characters, swapping alternate elements, or calculating frequencies.

Swapping Alternate Elements in a List

A favorite pattern asks you to swap adjacent elements of a list (index 0 with 1, 2 with 3, and so on).

def swap_alternate(arr):
    n = len(arr)
    for i in range(0, n - 1, 2):
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
    return arr


# Example execution
numbers = [1, 2, 3, 4, 5]
print("Original:", numbers)
print("Modified:", swap_alternate(numbers))

If the list has an odd number of elements, the loop condition range(0, n - 1, 2) or handling n // 2 ensures the last element remains untouched without causing an IndexError.

Quick checklist

  • [ ] Always import necessary modules (pickle, mysql.connector, math) at the very top of your code blocks.
  • [ ] Include explicit exception handling (try-except) for file operations and database connectivity.
  • [ ] Remember to use conn.commit() after executing INSERT, UPDATE, or DELETE SQL queries.
  • [ ] Check for boundary conditions like empty stacks or lists with odd/even lengths before writing loops.