Exam Prep
20 Important Python Programs for CBSE Class 12 Practical Exam 2026-27
Complete list of Python programs frequently asked in CBSE Class 12 Computer Science practical exam. File handling, stack, SQL connectivity with output.
The CBSE Class 12 Computer Science practical exam carries 30 marks. Here are the most frequently asked Python programs you must practice.
Program 1: Read and Display a Text File
def read_file():
f = open("story.txt", "r")
content = f.read()
print(content)
f.close()
read_file()
Program 2: Count Lines Starting with a Specific Letter
def count_lines(filename, letter):
f = open(filename, "r")
count = 0
for line in f:
if line.strip().startswith(letter):
count += 1
f.close()
return count
result = count_lines("story.txt", "T")
print("Lines starting with T:", result)
Program 3: Count Words in a Text File
def count_words(filename):
f = open(filename, "r")
content = f.read()
words = content.split()
f.close()
return len(words)
print("Total words:", count_words("story.txt"))
Program 4: Copy Lines Containing a Word to Another File
def copy_lines(source, dest, word):
f1 = open(source, "r")
f2 = open(dest, "w")
for line in f1:
if word in line:
f2.write(line)
f1.close()
f2.close()
copy_lines("story.txt", "output.txt", "Python")
Program 5: Read and Write CSV File
import csv
# Writing
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Marks", "Grade"])
writer.writerow(["Aman", 85, "A"])
writer.writerow(["Priya", 92, "A+"])
# Reading
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Output:
['Name', 'Marks', 'Grade']
['Aman', '85', 'A']
['Priya', '92', 'A+']
Program 6: Binary File, Write and Read Using Pickle
import pickle
# Writing
students = {"Aman": 85, "Priya": 92, "Rahul": 67}
with open("students.dat", "wb") as f:
pickle.dump(students, f)
# Reading
with open("students.dat", "rb") as f:
data = pickle.load(f)
print(data)
Output:
{'Aman': 85, 'Priya': 92, 'Rahul': 67}
Program 7: Stack Using List, Push and Pop
stack = []
def push(element):
stack.append(element)
print(f"Pushed: {element}")
def pop():
if not stack:
print("Stack Underflow!")
else:
return stack.pop()
def display():
if not stack:
print("Stack is empty")
else:
print("Stack:", stack[::-1])
push(10)
push(20)
push(30)
display()
print("Popped:", pop())
display()
Output:
Pushed: 10
Pushed: 20
Pushed: 30
Stack: [30, 20, 10]
Popped: 30
Stack: [20, 10]
Program 8: Count Uppercase, Lowercase, Digits, Special Characters
def count_chars(filename):
upper = lower = digits = special = 0
f = open(filename, "r")
content = f.read()
for ch in content:
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
elif ch.isdigit():
digits += 1
elif ch != ' ' and ch != '\n':
special += 1
f.close()
print(f"Uppercase: {upper}")
print(f"Lowercase: {lower}")
print(f"Digits: {digits}")
print(f"Special: {special}")
count_chars("story.txt")
Program 9: Python-MySQL Connectivity, Create and Insert
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS students (rollno INT PRIMARY KEY, name VARCHAR(50), marks INT)")
cursor.execute("INSERT INTO students VALUES (1, 'Aman', 85)")
cursor.execute("INSERT INTO students VALUES (2, 'Priya', 92)")
conn.commit()
print("Records inserted successfully")
cursor.close()
conn.close()
Program 10: Python-MySQL, Fetch and Display Records
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE marks > 80")
rows = cursor.fetchall()
for row in rows:
print(f"Roll: {row[0]}, Name: {row[1]}, Marks: {row[2]}")
cursor.close()
conn.close()
Output:
Roll: 1, Name: Aman, Marks: 85
Roll: 2, Name: Priya, Marks: 92
Program 11: Random Number Generator
import random
for i in range(5):
print(random.randint(1, 100), end=" ")
Program 12: Search in a Text File
def search_word(filename, word):
f = open(filename, "r")
line_num = 0
found = False
for line in f:
line_num += 1
if word in line:
print(f"Found '{word}' in line {line_num}: {line.strip()}")
found = True
if not found:
print(f"'{word}' not found in file")
f.close()
search_word("story.txt", "Python")
Program 13: Replace a Word in a File
def replace_word(filename, old, new):
f = open(filename, "r")
content = f.read()
f.close()
content = content.replace(old, new)
f = open(filename, "w")
f.write(content)
f.close()
print(f"Replaced '{old}' with '{new}'")
replace_word("story.txt", "Python", "PYTHON")
Program 14: Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
numbers = [64, 34, 25, 12, 22, 11, 90]
print("Sorted:", bubble_sort(numbers))
Output:
Sorted: [11, 12, 22, 25, 34, 64, 90]
Program 15: Binary Search
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [10, 20, 30, 40, 50, 60, 70]
pos = binary_search(numbers, 40)
print(f"Found at index: {pos}")
Output:
Found at index: 3
Program 16: Write and Read Student Records Using Binary File
import pickle
def write_students():
f = open("students.dat", "wb")
while True:
roll = int(input("Enter roll: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
record = [roll, name, marks]
pickle.dump(record, f)
choice = input("Add more? (y/n): ")
if choice.lower() == 'n':
break
f.close()
def read_students():
f = open("students.dat", "rb")
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
pass
f.close()
Program 17: Count Vowels and Consonants in a File
def count_vowels_consonants(filename):
vowels = consonants = 0
f = open(filename, "r")
content = f.read()
for ch in content.lower():
if ch.isalpha():
if ch in 'aeiou':
vowels += 1
else:
consonants += 1
f.close()
print(f"Vowels: {vowels}, Consonants: {consonants}")
count_vowels_consonants("story.txt")
Program 18: Exception Handling
def safe_divide():
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid numbers!")
finally:
print("Program completed")
safe_divide()
Program 19: Insertion Sort
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
numbers = [12, 11, 13, 5, 6]
print("Sorted:", insertion_sort(numbers))
Output:
Sorted: [5, 6, 11, 12, 13]
Program 20: MySQL, Update and Delete
import mysql.connector
conn = mysql.connector.connect(
host="localhost", user="root",
password="password", database="school"
)
cursor = conn.cursor()
# Update
cursor.execute("UPDATE students SET marks = 95 WHERE name = 'Aman'")
conn.commit()
print(f"Rows updated: {cursor.rowcount}")
# Delete
cursor.execute("DELETE FROM students WHERE marks < 50")
conn.commit()
print(f"Rows deleted: {cursor.rowcount}")
cursor.close()
conn.close()
Tips for the Practical Exam
- Always write comments - The examiner looks for them
- Test with sample data - Run your program before submitting
- Handle errors - Use try-except where applicable
- Use meaningful variable names - Not a, b, c
- Practice file operations - Text, binary, and CSV
Practice these programs daily. The CBSE practical exam is 30 marks, do not take it lightly.
Want to learn more?
Explore free chapter-wise notes with quizzes and code playground
Prefer watching over reading?
Subscribe for free.