---
title: "20 Python Programs for CBSE Class 12 Board Exam (083)"
description: "20 Python programs for the CBSE Class 12 Computer Science board exam: functions, text, binary and CSV files, and the stack, all tested with output."
slug: python-programs-for-cbse-class-12
canonical: https://learn.modernagecoders.com/blog/python-programs-for-cbse-class-12/
date: 2026-07-03
dateModified: 2026-07-03
category: "Programming"
tags: ["Python", "CBSE", "Class 12", "Computer Science", "Exam Preparation"]
keywords: ["python programs class 12", "cbse class 12 python programs", "class 12 computer science practical programs", "file handling programs class 12", "binary file programs python class 12", "stack program in python class 12", "csv programs class 12"]
readTime: "11 min read"
author: "Modern Age Coders"
---
# 20 Python Programs for CBSE Class 12 Board Exam (083)

> Functions, text files, binary files, CSV, and the stack: the program families the 083 paper keeps asking, each tested with its real output.

![20 Python programs for the CBSE Class 12 Computer Science board exam with tested code](/images/blog/python-programs-for-cbse-class-12/00-hero.png)

*By Modern Age Coders · 2026-07-03 · 11 min read*

If you are sitting the CBSE Class 12 Computer Science exam, code 083, the mathematics is simple: the programming unit is the biggest block of theory marks, and the practical adds 30 more on top. Most of those marks come from a small, predictable set of program types: functions, text files, binary files, CSV, and a stack.

This page collects **20 Python programs for CBSE Class 12** that cover exactly that ground. Each comes with the exam-style question and a working program, and every single one was executed before being pasted here, including the file-handling programs, which really created, read, and updated their files.

Type them, run them, then rewrite them from memory. The practical examiner is watching for fluency, not recital.

## Where These Programs Earn Their Marks

Computer Science (083) is split 70 and 30: a 70-mark theory paper, where Computational Thinking and Programming is the largest unit at 40 marks, and a 30-mark practical. Inside the practical, you write a Python program live for 8 marks, and your practical file, at least 15 Python programs plus SQL work, carries 7 more. In other words, the 20 programs below are aimed at the most concentrated marks in the whole subject.

![CBSE Class 12 Computer Science 083 marks split: 70 theory with programming worth 40, and 30 practical including the live Python program and practical file](/images/blog/python-programs-for-cbse-class-12/01-marks-map.png)

*Follow the marks. Programming dominates both halves of the subject.*

> **Build your practical file from this page**

> The board asks for a minimum of 15 Python programs in your practical file. The 20 here are organised to cover every required area, so working through them leaves your file effectively complete.

## The Files You Must Know Apart

Half the syllabus anxiety is really one confusion: which file type wants which tools. Text files use plain read and write. Binary files need the pickle module and rb or wb modes. CSV files use the csv module with reader and writer objects. Same idea, three dialects.

![Text versus binary versus CSV files in CBSE Class 12 Python: the open modes and modules each one uses](/images/blog/python-programs-for-cbse-class-12/02-file-trio.png)

*Three file types, three toolkits. Mixing them up costs marks.*

## Functions

Functions open the programming unit and the examiners love them because one question tests parameters, return values, and defaults all at once.

### 1. Palindrome check with a function

**Question:** Write a function is_palindrome(text) that returns True if the given string reads the same in both directions, ignoring case.

```python
def is_palindrome(text):
    text = text.lower()
    return text == text[::-1]

print(is_palindrome("Madam"))
print(is_palindrome("Python"))
```

```text
True
False
```

### 2. Count vowels with a function

**Question:** Write a function count_vowels(text) that returns the number of vowels in the given string.

```python
def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count = count + 1
    return count

print(count_vowels("Computer Science"))
```

```text
6
```

### 3. Simple interest with a default argument

**Question:** Write a function interest(principal, rate, time) where rate has a default value of 8, and show both ways of calling it.

```python
def interest(principal, time, rate=8):
    return principal * rate * time / 100

print(interest(5000, 2))        # uses the default rate
print(interest(5000, 2, 10))    # overrides it
```

```text
800.0
1000.0
```

### 4. Return several values at once

**Question:** Write a function that receives a list of marks and returns the highest, the lowest, and the average together.

```python
def summary(marks):
    return max(marks), min(marks), sum(marks) / len(marks)

high, low, avg = summary([78, 92, 65, 88, 71])
print("Highest:", high)
print("Lowest :", low)
print("Average:", avg)
```

```text
Highest: 92
Lowest : 65
Average: 78.8
```

## Text Files

Text file questions are near-guaranteed. Every one of them follows the same rhythm: open with the with clause, walk the content, count or copy something.

### 5. Create and write a text file

**Question:** Write a program to create a text file story.txt and write three lines into it using the with clause.

```python
with open("story.txt", "w") as f:
    f.write("Python is easy to learn.\n")
    f.write("The board exam tests files.\n")
    f.write("Practice makes it simple.\n")

print("story.txt created")
```

```text
story.txt created
```

### 6. Count words in a file

**Question:** Write a program to read story.txt and count the total number of words in it.

```python
with open("story.txt", "r") as f:
    text = f.read()

words = text.split()
print("Total words:", len(words))
```

```text
Total words: 14
```

### 7. Count lines starting with a vowel

**Question:** Write a program to count how many lines of story.txt begin with a vowel.

```python
count = 0
with open("story.txt", "r") as f:
    for line in f:
        if line and line[0].lower() in "aeiou":
            count = count + 1

print("Lines starting with a vowel:", count)
```

```text
Lines starting with a vowel: 0
```

### 8. Count character types in a file

**Question:** Write a program to count the uppercase letters, lowercase letters, and digits present in story.txt.

```python
upper = lower = digits = 0
with open("story.txt", "r") as f:
    for ch in f.read():
        if ch.isupper():
            upper = upper + 1
        elif ch.islower():
            lower = lower + 1
        elif ch.isdigit():
            digits = digits + 1

print("Uppercase:", upper)
print("Lowercase:", lower)
print("Digits   :", digits)
```

```text
Uppercase: 3
Lowercase: 59
Digits   : 0
```

### 9. Copy matching lines to another file

**Question:** Write a program to copy every line of story.txt that contains the word "exam" into a new file selected.txt.

```python
with open("story.txt", "r") as src, open("selected.txt", "w") as dest:
    for line in src:
        if "exam" in line.lower():
            dest.write(line)

with open("selected.txt", "r") as f:
    print(f.read().rstrip())
```

```text
The board exam tests files.
```

## Binary Files with pickle

Binary file questions carry the most steps: dump, load, search, update. Master this quartet and the scariest part of the practical becomes routine. These four programs run in sequence, exactly like a practical record.

![The pickle round trip in Python: a list of records goes through pickle.dump into a .dat file and comes back through pickle.load](/images/blog/python-programs-for-cbse-class-12/03-pickle-flow.png)

*dump on the way in, load on the way out. Everything binary is this round trip.*

### 10. Write records to a binary file

**Question:** Write a program using pickle to store a list of student records, each with roll, name, and marks, in a binary file students.dat.

```python
import pickle

students = [
    {"roll": 1, "name": "Asha", "marks": 92},
    {"roll": 2, "name": "Rohan", "marks": 85},
    {"roll": 3, "name": "Meera", "marks": 78}
]

with open("students.dat", "wb") as f:
    pickle.dump(students, f)

print("Records written:", len(students))
```

```text
Records written: 3
```

### 11. Read every record back

**Question:** Write a program to open students.dat and display every stored record.

```python
import pickle

with open("students.dat", "rb") as f:
    students = pickle.load(f)

for s in students:
    print(s["roll"], s["name"], s["marks"])
```

```text
1 Asha 92
2 Rohan 85
3 Meera 78
```

### 12. Search a binary file by roll number

**Question:** Write a program to search students.dat for the record with roll number 2 and display it, or report that it is missing.

```python
import pickle

with open("students.dat", "rb") as f:
    students = pickle.load(f)

found = False
for s in students:
    if s["roll"] == 2:
        print("Found:", s["name"], "with", s["marks"], "marks")
        found = True

if not found:
    print("No record with that roll number")
```

```text
Found: Rohan with 85 marks
```

### 13. Update a record and save it back

**Question:** Write a program to increase Rohan's marks by 5 in students.dat and rewrite the file.

```python
import pickle

with open("students.dat", "rb") as f:
    students = pickle.load(f)

for s in students:
    if s["name"] == "Rohan":
        s["marks"] = s["marks"] + 5

with open("students.dat", "wb") as f:
    pickle.dump(students, f)

with open("students.dat", "rb") as f:
    print(pickle.load(f)[1])
```

```text
{'roll': 2, 'name': 'Rohan', 'marks': 90}
```

## CSV Files

CSV connects Python to spreadsheets, and the csv module does the heavy lifting. Remember newline="" when writing, and next(reader) to skip a header.

### 14. Write rows to a CSV file

**Question:** Write a program using the csv module to create results.csv with a header row and three student rows.

```python
import csv

rows = [
    ["Roll", "Name", "Marks"],
    [1, "Asha", 92],
    [2, "Rohan", 85],
    [3, "Meera", 78]
]

with open("results.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

print("results.csv written")
```

```text
results.csv written
```

### 15. Read a CSV file row by row

**Question:** Write a program to read results.csv and display each row.

```python
import csv

with open("results.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
```

```text
['Roll', 'Name', 'Marks']
['1', 'Asha', '92']
['2', 'Rohan', '85']
['3', 'Meera', '78']
```

### 16. Filter and total a CSV file

**Question:** Write a program to count how many students in results.csv scored more than 80, skipping the header row.

```python
import csv

count = 0
with open("results.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)                 # skip the header
    for row in reader:
        if int(row[2]) > 80:
            count = count + 1

print("Students above 80:", count)
```

```text
Students above 80: 2
```

## The Stack

The syllabus names one data structure: a stack implemented with a list. Push with append, pop with pop, and respect the underflow case.

![A stack implemented with a Python list: push with append and pop from the same end, last in first out](/images/blog/python-programs-for-cbse-class-12/04-stack.png)

*One end does all the work. Last in, first out.*

### 17. Implement a stack using a list

**Question:** Write a program to implement push, pop, and peek operations for a stack of book titles using a list.

```python
stack = []

def push(item):
    stack.append(item)

def pop():
    if not stack:
        return "Underflow"
    return stack.pop()

def peek():
    if not stack:
        return "Empty"
    return stack[-1]

push("Maths")
push("Physics")
push("CS")

print("Top of stack:", peek())
print("Popped:", pop())
print("Popped:", pop())
print("Remaining:", stack)
```

```text
Top of stack: CS
Popped: CS
Popped: Physics
Remaining: ['Maths']
```

### 18. Reverse a string using a stack

**Question:** Write a program that pushes every character of a word onto a stack, then pops them all to build the reversed word.

```python
word = "BOARDS"
stack = []

for ch in word:
    stack.append(ch)

reversed_word = ""
while stack:
    reversed_word = reversed_word + stack.pop()

print(reversed_word)
```

```text
SDRAOB
```

## Random Numbers and Dictionaries

Two final favourites: the random module, which powers dice and OTP style questions, and the dictionary counting pattern that turns up in output-prediction questions too.

### 19. Dice roller with random

**Question:** Write a program using the random module to simulate rolling a die five times. The output changes every run, which is the point.

```python
import random

for i in range(5):
    print("Roll", i + 1, ":", random.randint(1, 6))
```

```text
Roll 1 : 6
Roll 2 : 6
Roll 3 : 6
Roll 4 : 3
Roll 5 : 4
```

### 20. Word frequency with a dictionary

**Question:** Write a program to count how many times each word appears in a sentence, using a dictionary.

```python
sentence = "the exam tests the file the stack and the loop"

counts = {}
for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1

for word, n in counts.items():
    print(word, "->", n)
```

```text
the -> 4
exam -> 1
tests -> 1
file -> 1
stack -> 1
and -> 1
loop -> 1
```

## The Marks You Lose Without Noticing

- **Wrong mode for binary files:** opening students.dat with "r" instead of "rb" crashes pickle. Binary files always take the b.
- **Forgetting newline="" when writing CSV:** without it, Windows inserts a blank line after every row, and your output looks wrong in the viva.
- **Popping an empty stack:** always check the underflow case. Examiners deliberately test it.
- **Reading a file after writing without reopening:** finish the with block, then open again to read. The with clause closes the file for you.
- **Hard-coding what should be a parameter:** if the question says any file or any number, your function must accept it as an argument.

> **A four-week plan that works**

> Week one, functions and text files. Week two, binary and CSV. Week three, the stack plus your project polishing. Week four, rewrite one program from each family from memory every day. Steady beats heroic, especially in board season.

---

## Frequently Asked Questions

**Which Python programs are most important for the CBSE Class 12 board exam?**

Text file programs (counting words, lines, or characters), binary file programs with pickle (write, read, search, update), CSV reading and writing, a stack implemented with a list, and function-based questions. The 20 programs on this page cover all of these families.

**How many marks is the Computer Science practical?**

The practical carries 30 marks alongside the 70-mark theory paper. Within it, the live Python program is worth 8 marks and the practical file, with a minimum of 15 Python programs plus SQL work, carries 7, with the project and viva making up the rest.

**What is the difference between a text file and a binary file in Python?**

A text file stores readable characters and is handled with plain read and write in "r" or "w" modes. A binary file stores Python objects in encoded form, needs "rb" or "wb" modes, and uses the pickle module's dump and load to convert objects to bytes and back.

**Why do we use pickle in Class 12 Python?**

pickle converts whole Python objects, like a list of student dictionaries, into bytes that can be saved in a binary file, and converts them back on reading. That lets record-style programs store structured data without inventing a text format.

**What does newline="" do when writing a CSV file?**

It stops Python from adding an extra blank line after every row on Windows. The csv module manages its own line endings, so you hand it a file opened with newline="" and let it take charge.

**How is a stack implemented in Python for the board exam?**

With a plain list, using append() to push and pop() to remove, both at the same end. The syllabus expects push, pop, and usually peek or display, plus handling of the underflow case when the stack is empty.

**Is Class 12 Computer Science hard to score in?**

It is considered one of the more scoring subjects precisely because the program types repeat. If you can write the file-handling and stack programs fluently and manage your SQL, the paper holds few surprises. Consistent practice matters more than brilliance.

## Walk Into the Practical Calm

Twenty programs, six families, and between them the whole programming side of the 083 paper. The pattern you should notice: none of these programs is long. Board programs reward clarity and correct tool choice, not cleverness. If a program here felt shaky, that family is your next practice session. For the underlying concepts, our [file handling guide](/blog/how-to-read-and-write-files-in-python) and [exception handling guide](/blog/exception-handling-in-python) go deeper.

And if you want a teacher who has walked students through this exact paper, our [Python classes for Class 12 CBSE](/python-for-class-12-cbse) run live and hands-on, with [courses](/courses) for learners aged 6 to 67.

[Prepare With a Class 12 Teacher](/python-for-class-12-cbse)

### Related reading

- [How to Read and Write Files in Python](/blog/how-to-read-and-write-files-in-python)
- [Exception Handling in Python](/blog/exception-handling-in-python)
- [Python Dictionary: The Complete Guide](/blog/python-dictionary-complete-guide)

---

*Source: https://learn.modernagecoders.com/blog/python-programs-for-cbse-class-12/*
