CBSE Class 12 Python programs practical file Computer Science 2027 Python file handling programs stack implementation Python MySQL Python connectivity Matplotlib programs CBSE binary file handling pickle CSV file handling Python sorting algorithms Python CBSE CS practical exam viva voce questions Python bubble sort insertion sort binary search

CBSE Class 12 Python: 100+ Programs for Practical File & Board Exam (2027)

T

Tushar Parik

Author

Updated 14 March 2026
21 min read

100+ Python Programs Every CBSE Class 12 Student Needs in 2027

The CBSE Class 12 Computer Science practical exam (2026–27 session) carries 30 marks — 21 for the practical file and lab test, 7 for the project, and 2 for the viva voce. That is nearly one-third of your total score. This guide organises 100+ Python programs by topic — from basic string manipulation to Matplotlib data visualisation — covering every category the CBSE syllabus demands. Each section includes program descriptions, code patterns, expected outputs, and viva questions so you walk into the exam room fully prepared. Whether you are building your practical file, revising for the theory paper, or practising for the viva, this is your single reference.

In This Article

Why Python Practicals Matter for Your Board Score

The CBSE Computer Science (083) practical examination for 2026–27 is structured as follows:

Component Marks What Examiners Check
Lab Test (Python) 8 One program from the practical file; must write, execute, and show output
Lab Test (SQL) 5 SQL queries on a given table; must write and execute on MySQL
Practical File (20 programs) 8 Neatness, correctness, variety of topics, output screenshots
Project 7 Working project with documentation
Viva Voce 2 Conceptual understanding of programs and Python fundamentals

Your practical file must contain a minimum of 20 programs spanning at least six categories. The 100+ programs listed below give you far more than enough to choose from — pick the ones that best demonstrate breadth and complexity.

String Manipulation Programs

Strings are immutable sequences in Python and one of the most commonly tested data types. CBSE examiners expect you to work with indexing, slicing, built-in methods, and character-level operations without importing external libraries.

# Program Key Concepts Tested
1 Count vowels, consonants, digits, and special characters in a string Iteration, isalpha(), isdigit(), membership operator
2 Check if a string is a palindrome Slicing ([::-1]), comparison operators
3 Count the frequency of each word in a string split(), dictionary accumulation
4 Replace all spaces with hyphens in a given string replace(), string immutability
5 Convert uppercase to lowercase and vice versa (swap case) swapcase() or manual ord()/chr() conversion
6 Remove all duplicate characters from a string Iteration, membership check, string concatenation
7 Find the longest word in a sentence split(), len(), max() with key
8 Check whether a string contains only alphabets isalpha(), boolean return values
9 Count uppercase and lowercase letters separately isupper(), islower(), counter variables
10 Display each word of a string in reverse order (not the string itself) split(), reversed(), join()
11 Accept a string and display it in title case without using title() Manual case conversion, space-based word detection
12 Extract and display all digits from a string isdigit(), string traversal

Practical File Tip

Include at least 3 string programs in your file. Programs 1, 3, and 5 are the most frequently asked in lab tests. Always show sample input and output in your file — examiners award marks for clear documentation.

List, Tuple & Dictionary Programs

Lists are mutable, tuples are immutable, and dictionaries store key-value pairs. CBSE expects you to demonstrate all three with programs that show insertion, deletion, searching, sorting, and nested structures.

# Program Key Concepts Tested
13 Linear search in a list of numbers Sequential search, index tracking, flag variable
14 Binary search in a sorted list Divide and conquer, mid calculation, while loop
15 Selection sort on a list of integers Nested loops, minimum element, swap logic
16 Insertion sort on a list of integers Key element, shifting logic, while loop inside for loop
17 Bubble sort on a list of integers Adjacent comparison, swap, pass tracking
18 Find the second largest element in a list without using sort() Two-variable tracking, conditional updates
19 Remove all duplicate elements from a list Membership check, new list construction
20 Merge two sorted lists into a single sorted list Two-pointer technique, list concatenation
21 Create a dictionary from two lists (keys and values) zip(), dict comprehension
22 Count the frequency of elements in a list using a dictionary Dictionary accumulation, get() method
23 Sort a dictionary by values in ascending and descending order sorted() with lambda, items()
24 Create a histogram from a dictionary of student marks Iteration, formatted output, * operator for repetition
25 Input n student records (roll, name, marks) into a list of tuples and display Tuple packing, list of tuples, formatted output
26 Find the union, intersection, and difference of two lists Set operations, type conversion, list comprehension

Board Exam Pattern Alert

Binary search and sorting algorithms (bubble sort, insertion sort) are compulsory topics in the 2027 theory paper. Programs 14–17 are non-negotiable for your practical file. The theory paper also asks you to trace through sorting algorithms step by step, so practise dry runs on paper alongside coding.

Functions & Recursion Programs

Functions test your ability to modularise code. CBSE specifically expects user-defined functions with default arguments, keyword arguments, and return values. Recursion — a function calling itself — is a favourite in both practicals and theory.

# Program Key Concepts Tested
27 Factorial of a number using recursion Base case, recursive call, return value
28 Fibonacci series using recursion Double recursion, base cases (0 and 1)
29 Sum of digits of a number using recursion Modulo operator, integer division, recursion
30 Power of a number (xn) using recursion Recursive multiplication, base case n==0
31 GCD of two numbers using recursion (Euclidean algorithm) Modulo, swap logic, recursive reduction
32 Function with default and keyword arguments to calculate simple interest Default parameters, keyword arguments, return
33 Function to check if a number is prime Loop optimisation (check up to √n), boolean return
34 Function to return both maximum and minimum from a list (multiple return values) Tuple return, unpacking
35 Variable-length arguments: function to accept any number of integers and return their sum *args, iteration over arguments

Text & Binary File Handling Programs

File handling is the most heavily weighted topic in CBSE Class 12 Computer Science — it appears in both the theory paper (12–15 marks) and the practical exam. You must demonstrate text file operations (read(), readline(), readlines(), write()) and binary file operations (pickle.dump(), pickle.load()).

# Program Key Concepts Tested
36 Write user-entered text to a file and display its contents open(), write(), read(), file modes (w, r)
37 Count lines, words, and characters in a text file readlines(), split(), len()
38 Read a text file and count occurrences of a specific word read(), lower(), split(), count()
39 Read a file and display all lines starting with a vowel readline(), string indexing, conditional check
40 Copy contents of one text file to another, replacing a specific word Two file handles, replace(), read-write cycle
41 Read a text file and display lines containing “the” (case-insensitive) lower(), in operator, line-by-line reading
42 Write student records (roll, name, marks) to a binary file using pickle pickle.dump(), wb mode, list of dictionaries
43 Read student records from a binary file and display all with marks > 80 pickle.load(), rb mode, EOFError handling
44 Search for a specific record in a binary file by roll number try-except with EOFError, sequential read, flag
45 Update a record in a binary file (modify marks by roll number) seek(), tell(), read-modify-write pattern
46 Delete a record from a binary file by roll number Read all, filter, rewrite — no in-place deletion in binary files
47 Display file pointer position using tell() and move it using seek() File pointer concepts, seek(offset, whence)
48 Append new records to an existing binary file ab mode, pickle.dump() for each record

Critical Viva Point: Text vs Binary Files

In the viva, examiners almost always ask: “What is the difference between text and binary files?” The answer: text files store data as readable characters (ASCII/UTF-8), while binary files store data in the same format as it is stored in memory (using pickle serialisation in Python). Binary files are not human-readable but are faster for structured data like records.

CSV File Handling Programs

CSV (Comma Separated Values) file handling was added to the CBSE syllabus in 2020 and has appeared in every board exam since. You must use the csv module — not manual string splitting.

# Program Key Concepts Tested
49 Write student data (roll, name, marks) to a CSV file csv.writer(), writerow(), writerows()
50 Read and display all data from a CSV file csv.reader(), iteration, row unpacking
51 Search for a specific record in a CSV file by roll number csv.reader(), conditional check, type conversion
52 Count the number of records in a CSV file Row counting, skipping header row
53 Write and read data using csv.DictWriter() and csv.DictReader() Dictionary-based CSV I/O, fieldnames parameter
54 Append new records to an existing CSV file a mode with csv.writer(), newline='' parameter

Common CSV Mistake

Always include newline='' when opening CSV files on Windows to prevent blank rows between records. This is a one-mark deduction in many schools if missing. The syntax is: open('file.csv', 'w', newline='').

Stack Implementation Using Lists

The stack data structure (LIFO — Last In First Out) is a compulsory practical topic in CBSE Class 12. You must implement push, pop, peek, and display operations using a Python list. The 2027 theory paper will also test stack tracing.

# Program Key Concepts Tested
55 Stack of integers with push, pop, peek, and display append(), pop(), [-1] indexing, underflow check
56 Stack of strings — push names and pop them Same operations, string data type in stack
57 Stack of dictionaries — push employee records and pop them Nested data structures, dictionary inside list
58 Reverse a string using a stack Push each character, pop all to build reversed string
59 Check balanced parentheses using a stack Push on open bracket, pop on close, match check
60 Convert decimal to binary using a stack Repeated division by 2, push remainders, pop to display

Examiner Expectation

Your stack program must include an overflow check (if you set a maximum size) and an underflow check (check if the stack is empty before popping). Programs without these checks lose marks in the practical exam. Also include a menu-driven interface — examiners appreciate user-friendly programs.

SQL Connectivity & Query Programs

CBSE requires students to connect Python with MySQL using the mysql.connector module. The practical file must contain programs that execute SQL queries from Python and fetch results. The lab test may ask you to write and run SQL queries on a given database.

# Program Key Concepts Tested
61 Connect to MySQL database and display all databases mysql.connector.connect(), cursor(), execute()
62 Create a table, insert records, and display them CREATE TABLE, INSERT INTO, SELECT, fetchall()
63 Insert a record using user input (parameterised query) Parameterised queries (%s placeholders), commit()
64 Update a record based on a condition entered by the user UPDATE SET WHERE, rowcount, commit()
65 Delete a record based on user input DELETE FROM WHERE, confirmation prompt, commit()
66 Display records using WHERE clause with user-entered condition fetchall() vs fetchone(), dynamic queries
67 Perform aggregate queries (COUNT, SUM, AVG, MAX, MIN) from Python Aggregate functions, fetchone(), result extraction
68 Display records in sorted order (ORDER BY) from Python ORDER BY ASC/DESC, formatted table output
69 GROUP BY query with HAVING clause from Python GROUP BY, HAVING, displaying grouped results
70 Menu-driven program for complete CRUD operations on a student table Full integration: connect, create, read, update, delete, menu

SQL Lab Test Essentials

  • Always use parameterised queries (%s placeholders) instead of string formatting to prevent SQL injection — examiners specifically check for this.
  • Call commit() after INSERT, UPDATE, and DELETE — otherwise changes are not saved to the database.
  • Handle exceptions with try-except blocks — a crashed program loses all marks in the lab test.
  • Close the connection at the end — always include conn.close() in your programs.

Data Visualisation with Matplotlib

Matplotlib was added to the CBSE syllabus to teach data visualisation. The practical file must include at least 2–3 chart programs. The theory paper tests pyplot functions, chart types, and customisation options.

# Program Key Concepts Tested
71 Line chart: Plot student marks across five subjects plt.plot(), xlabel(), ylabel(), title(), show()
72 Line chart with multiple lines: Compare marks of two students Multiple plt.plot() calls, legend(), colour and marker
73 Bar chart: Display population of five cities plt.bar(), bar width, colour customisation
74 Horizontal bar chart: Compare sales of products plt.barh(), horizontal layout
75 Histogram: Display frequency distribution of student marks plt.hist(), bins, edgecolor
76 Pie chart: Show percentage share of expenses plt.pie(), autopct, explode, shadow
77 Customised line chart with grid, legend, linestyle, and marker grid(), linestyle, marker, linewidth
78 Save a chart as a PNG image file plt.savefig(), dpi parameter, file format
79 Subplots: Display bar chart and pie chart side by side plt.subplot(), figure layout, tight_layout
80 Read data from a CSV and plot it as a bar chart Integration of csv module with matplotlib

Additional Programs for Extra Practice

The following programs are bonus practice questions that cover edge cases, combinations of topics, and common board exam patterns. Including a few of these in your practical file shows depth beyond the minimum requirement.

Number-Based Programs

  • 81. Check Armstrong number
  • 82. Generate prime numbers in a range
  • 83. Display Pascal's triangle
  • 84. Check if a number is a perfect number
  • 85. Generate the first n terms of a Fibonacci series (iterative)
  • 86. Convert decimal to octal and hexadecimal

Pattern & Matrix Programs

  • 87. Display a right-angled triangle pattern of stars
  • 88. Display a diamond pattern of numbers
  • 89. Transpose of a matrix using nested lists
  • 90. Add two matrices
  • 91. Multiply two matrices

Advanced File & Integration Programs

  • 92. Read a text file and create a new file with lines in reverse order
  • 93. Merge two CSV files into one
  • 94. Read marks from a binary file and plot a bar chart using Matplotlib
  • 95. Random number generator game (guess the number)
  • 96. Menu-driven program combining file handling and stack

SQL Query Practice (Theory Paper)

  • 97. SELECT with WHERE, AND, OR, NOT
  • 98. SELECT with BETWEEN, IN, LIKE
  • 99. JOIN two tables (equi-join)
  • 100. Subqueries with IN and EXISTS
  • 101. ALTER TABLE — add/drop/modify column
  • 102. CREATE VIEW and query from it

How to Organise Your Practical File for Maximum Marks

A well-organised practical file can be the difference between 6/8 and 8/8 marks. Follow this structure for every program.

Structure for Each Program

  1. Program Number and Title — e.g., “Program 5: Swap Case of a String”
  2. Aim/Objective — One line stating what the program does
  3. Source Code — Neatly printed or handwritten (printed is preferred in 2027)
  4. Sample Output — Screenshot or printed output showing actual execution
  5. Variable Description Table — (Optional but recommended) List each variable, its type, and purpose

Recommended 20-Program Selection for Your Practical File

Category Count Recommended Programs (from list above)
String Manipulation 3 #1, #3, #5
List / Sorting / Searching 3 #14, #17, #22
Functions / Recursion 2 #27, #28
Text File Handling 3 #37, #38, #40
Binary File Handling 2 #42, #44
CSV File Handling 2 #49, #50
Stack Implementation 1 #55
Python-MySQL Integration 2 #62, #70
Data Visualisation 2 #71, #76

Top 30 Viva Voce Questions & Answers

The viva voce carries only 2 marks, but it can make or break a borderline score. Examiners typically ask 4–6 rapid-fire questions. Here are the 30 most commonly asked ones.

Python Fundamentals

  1. What is the difference between a list and a tuple? — Lists are mutable (can be changed), tuples are immutable (cannot be changed after creation).
  2. What is a dictionary? — An unordered collection of key-value pairs where keys must be unique and immutable.
  3. What is the difference between == and is?== checks value equality, is checks identity (same object in memory).
  4. What are mutable and immutable types? — Mutable: list, dict, set. Immutable: int, float, str, tuple.
  5. What is the scope of a variable? — Local (inside function), global (module level), built-in (Python built-ins).

File Handling

  1. What are the file opening modes? — r (read), w (write), a (append), rb (read binary), wb (write binary), ab (append binary).
  2. What does pickle module do? — Serialises Python objects into byte streams (dump) and deserialises them back (load).
  3. What is the difference between read() and readlines()?read() returns entire file as one string; readlines() returns a list of lines.
  4. What does seek() do? — Moves the file pointer to a specific position. seek(0) moves to the beginning.
  5. Why do we use with statement for files? — It automatically closes the file after the block, even if an error occurs.

Functions & Recursion

  1. What is recursion? — A function calling itself to solve a smaller subproblem. Requires a base case to stop.
  2. What is a base case? — The condition that stops recursive calls. Without it, you get infinite recursion (stack overflow).
  3. What is the difference between actual and formal parameters? — Actual: values passed during function call. Formal: variables in function definition.
  4. What are *args and **kwargs?*args collects positional arguments as a tuple. **kwargs collects keyword arguments as a dictionary.
  5. What is a lambda function? — An anonymous one-line function defined using lambda keyword. Used for short operations.

Stacks & SQL

  1. What is a stack? — A linear data structure following LIFO (Last In First Out) principle.
  2. What is overflow and underflow? — Overflow: pushing to a full stack. Underflow: popping from an empty stack.
  3. Which Python list methods implement push and pop?append() for push, pop() for pop.
  4. What is commit() in MySQL? — Saves all pending changes to the database. Without it, INSERT/UPDATE/DELETE are not permanent.
  5. What is a parameterised query? — A query using %s placeholders instead of string formatting, preventing SQL injection.

Data Visualisation & Advanced

  1. What is Matplotlib? — A Python library for creating static, animated, and interactive data visualisations.
  2. Name four types of charts in Matplotlib. — Line chart, bar chart, histogram, pie chart.
  3. What is the difference between a bar chart and a histogram? — Bar chart: categorical data with gaps. Histogram: continuous data, no gaps between bars.
  4. What does plt.legend() do? — Displays a legend box identifying each plotted data series by label.
  5. What is the difference between fetchone() and fetchall()?fetchone() returns one row as a tuple. fetchall() returns all rows as a list of tuples.

Sorting & Searching

  1. What is the time complexity of bubble sort? — O(n²) in worst and average cases.
  2. Why is binary search faster than linear search? — Binary search is O(log n) vs O(n), but requires a sorted list.
  3. What is the difference between selection sort and insertion sort? — Selection sort finds the minimum and swaps. Insertion sort shifts elements and inserts in the correct position.
  4. What is the csv module used for? — Reading from and writing to CSV files using reader(), writer(), DictReader(), DictWriter().
  5. What is exception handling? — Using try-except blocks to gracefully handle runtime errors instead of crashing the program.

Frequently Asked Questions

Q: How many programs should I include in my CBSE Class 12 Computer Science practical file?

The CBSE minimum requirement is 20 programs. However, including 22–25 programs is recommended because examiners appreciate variety. Your file should cover at least six categories: string manipulation, list operations, file handling (text and binary), CSV, stack implementation, and Python-MySQL connectivity. Adding 2–3 Matplotlib programs strengthens your file further.

Q: Which topics carry the most marks in the CBSE Class 12 CS theory paper?

File handling (text, binary, and CSV) carries approximately 12–15 marks. Data structures (stack implementation and SQL queries) carry 10–12 marks. Functions and recursion carry 6–8 marks. Data visualisation with Matplotlib carries 4–6 marks. Together, these four topics account for over 70 percent of the theory paper, making the programs in this guide directly relevant to your board preparation.

Q: Do I need to memorise all 100 programs for the board exam?

No. You need to understand the logic behind each program category. Once you grasp how file handling works with open(), read(), write(), and pickle, you can solve any file-related question the examiner gives you. Focus on understanding 3–4 representative programs from each category rather than rote-memorising all 100. The theory paper tests concepts and logic tracing, not exact code reproduction.

Q: What IDE should I use for CBSE Class 12 Python practicals?

CBSE officially recommends Python IDLE, which comes pre-installed with Python. Most schools also accept VS Code, Thonny, or PyCharm Community Edition. For the practical exam, you will typically use whatever IDE is installed in your school lab. It is wise to practise on IDLE because that is the most common exam environment. For MySQL connectivity, you will need MySQL Server installed alongside Python, with the mysql-connector-python package.

Q: How do I install MySQL Connector and Matplotlib for the practical exam?

Open Command Prompt (Windows) or Terminal (Mac/Linux) and run: pip install mysql-connector-python for MySQL connectivity and pip install matplotlib for data visualisation. If you get a permission error, use pip install --user mysql-connector-python. In your school lab, these packages should already be installed. If they are not, ask your teacher to install them before the exam.

Q: What is the most common mistake students make in the practical exam?

The single most common mistake is not handling exceptions. When a binary file program crashes because of an EOFError that was not caught in a try-except block, the student loses all marks for that question. The second most common mistake is forgetting to call commit() after SQL INSERT, UPDATE, or DELETE operations. Always test your program with edge cases (empty file, no matching record, incorrect input) before submitting.

Q: Can I use this program list for ISC (ICSE Class 12) Computer Science as well?

The ISC Computer Science syllabus uses Java, not Python, so these programs do not directly apply. However, the data structure concepts (stack, searching, sorting) and SQL query patterns are common to both boards. If your ISC school offers Python as an elective or if you are preparing for competitive coding, these programs are excellent practice. For ISC-specific Java programs, check our dedicated ISC guide.

Q: When should I start preparing my practical file for the 2027 exam?

Start your practical file by August 2026, immediately after your school begins the Class 12 session. Complete at least 2–3 programs per week so that your file is ready by December 2026, well before the practical exam window (typically January–February 2027). This gives you time to test every program, take proper output screenshots, and get your teacher's signature on each page. Last-minute file preparation leads to errors and incomplete documentation.

Your Practical File Is 30 Marks — Do Not Leave Them on the Table

The CBSE Class 12 Computer Science practical exam is one of the most scoring components of the entire board examination. Every program you practise today is a mark you secure tomorrow. Start with the recommended 20-program selection, master each category, prepare for the viva, and walk into the exam with complete confidence.

Need structured coaching for CBSE Class 12 Computer Science? Bright Tutorials offers expert guidance with hands-on lab sessions, project mentoring, and full practical file preparation. Reach out today.

About Bright Tutorials

Bright Tutorials is a trusted coaching institute in Nashik, providing expert guidance for CBSE, ICSE, SSC, and competitive exam preparation since 2015.

Address: Shop No. 53-57, Business Signature, Hariom Nagar, Nashik Road, Nashik, Maharashtra 422101

Google Maps: Get Directions

Phone: +91 94037 81999 | +91 94047 81990

Email: info@brighttutorials.in | Website: brighttutorials.in

Read More on Bright Tutorials Blog

You May Also Like

Tags: CBSE Class 12 Python programs practical file Computer Science 2027 Python file handling programs stack implementation Python MySQL Python connectivity Matplotlib programs CBSE binary file handling pickle CSV file handling Python sorting algorithms Python CBSE CS practical exam viva voce questions Python bubble sort insertion sort binary search

Comments

0

No comments yet. Be the first to share your thoughts!

Sign in to join the conversation and leave a comment.

Sign in to comment