Edumath by Sereddy logo

Computer Science Class 12: Python Programs That Repeat in CBSE Exams

27 August 2026 · Yesunadhareddy SereddyComputer SciencePythonClass 12CBSE Board Exams

CBSE Class 12 Computer Science paper relies heavily on logical pattern repetition in the coding sections. Whether you are following the latest NCERT syllabus, preparing for board exams under NCF-SE guidelines, or brushing up for state board and competitive tests, certain Python program types appear every single year with minor data tweaks.

Knowing how to structure these programs and handling edge cases will secure full marks in your practical and theory coding questions. Let's break down the core categories of Python programs that examiners love to repeat.

1. File Handling: Text and Binary Files

File handling is the highest-weighted coding section in the Class 12 Computer Science paper. Questions here usually ask you to read from an existing file, process the content, and write or display the output.

Reading and Filtering Text Files

Examiners frequently ask programs that count specific words, lines, or characters, or extract lines starting with a particular letter.

def count_the_articles():
    file = open("story.txt", "r")
    count = 0
    for line in file:
        words = line.split()
        for word in words:
            # Case-insensitive check for 'the'
            if word.lower() == "the":
                count += 1
    file.close()
    print("Total 'the' present:", count)

Common variations of this question include:

  • Displaying all lines that do not start with 'A' or 'S'.
  • Replacing a specific word with another word in a text file.
  • Copying lines containing a specific substring to another file.

Binary Files using pickle

Binary file questions test your ability to use Python's built-in pickle module. You must know how to dump() records (usually dictionaries or lists packed inside a structure) and load() them until an EOFError occurs.

import pickle


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


def read_binary():
    file = open("student.dat", "rb")
    try:
        while True:
            rec = pickle.load(file)
            if rec[2] > 75:  # Display students scoring above 75
                print(f"Roll No: {rec[0]}, Name: {rec[1]}, Marks: {rec[2]}")
    except EOFError:
        pass
    file.close()

2. Stack Implementation using Lists

In data structures, implementing a Stack in Python using a list is a staple question. Examiners test your understanding of LIFO (Last In, First Out) operations along with pointer management (the top variable).

def isEmpty(stk):
    if len(stk) == 0:
        return True
    return False


def Push(stk, item):
    stk.append(item)
    top = len(stk) - 1


def Pop(stk):
    if isEmpty(stk):
        return "Underflow"
    else:
        item = stk.pop()
        return item


def Display(stk):
    if isEmpty(stk):
        print("Stack is empty")
    else:
        top = len(stk) - 1
        print(stk[top], "<-- Top")
        for i in range(top - 1, -1, -1):
            print(stk[i])

Board questions often frame this around real-world scenarios: pushing and popping employee records, book details, or customer IDs based on specific conditions (e.g., pushing elements only if an ID is even).

3. Database Connectivity (Python + MySQL)

Database connectivity bridges your SQL knowledge with Python programming. You are required to import the connector module, establish a connection, create a cursor, and execute queries.

| Operation Type | Typical Python Method Used | | :--- | :--- | | Connection Setup | mysql.connector.connect(host=..., user=..., password=..., database=...) | | Execution | cursor.execute("SQL_QUERY_STRING") | | Fetching Results | cursor.fetchone() or cursor.fetchall() | | Saving Changes | mydb.commit() |

Here is a standard fetch query program that repeats in exams:

import mysql.connector


def get_high_scorers():
    mydb = mysql.connector.connect(
        host="localhost", user="root", password="password", database="school"
    )
    cursor = mydb.cursor()

    # Executing select query
    cursor.execute("SELECT * FROM student WHERE marks > 80")
    records = cursor.fetchall()

    for row in records:
        print(f"Roll: {row[0]}, Name: {row[1]}, Marks: {row[2]}")

    cursor.close()
    mydb.close()

4. Random Module Programs

Questions involving the random module test your ability to generate random integers or select items from sequences within specific numerical boundaries.

import random

# Generate a random integer between 1 and 6 (inclusive) like a dice roll
dice = random.randint(1, 6)

# Generate a random number from a sequence with a step (e.g., multiples of 3 between 10 and 20)
# randrange(start, stop, step)
val = random.randrange(10, 21, 3)

# Choosing from a list
colors = ["Red", "Green", "Blue", "Yellow"]
picked = random.choice(colors)

Pay close attention to boundary values in exam questions. For instance, if a question asks for a random integer from 11 to 1010 inclusive, randint(1, 10) must be used instead of randrange(1, 10).

Quick Checklist for Exam Day

  • [ ] Always close files: Use .close() explicitly or manage file pointers properly to avoid losing marks.
  • [ ] Handle exceptions: Wrap binary file reading loops inside try...except EOFError: blocks.
  • [ ] Include commit statements: In MySQL-Python programs, remember to invoke mydb.commit() after INSERT, UPDATE, or DELETE operations.
  • [ ] Check indentation: Python relies heavily on precise indentation. Misaligned blocks lead to syntax or logic errors.
  • [ ] Import modules: Never forget to write import pickle, import mysql.connector, or import random at the top of your code snippet when required.