Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🏆 Revision & Practice  ·  Lesson 25

Important Programs (Practical File)

Programs list

These programs follow the common practical-file list. Each program is complete and tested; the output shown is the real output. Files created by one program (story.txt) are used by the next ones, so run them in order.

🧮
FunctionsProgram 1
📄
Text filesPrograms 2–4, 11
💾
Binary filesPrograms 5–6
🎲
RandomProgram 7
📊
CSVProgram 8
📚
StackProgram 9
🔎
Sort/SearchProgram 10
🛢️
MySQLConnectivity lesson
What is covered

Functions

Python
# 1. Menu-driven program using user-defined functions
def factorial(n):
    f = 1
    for i in range(2, n + 1):
        f *= i
    return f
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
def fibonacci(n):
    a, b, out = 0, 1, []
    for _ in range(n):
        out.append(a); a, b = b, a + b
    return out
ch = int(input('1.Factorial 2.Prime 3.Fibonacci : '))
n = int(input('Enter n: '))
if ch == 1:
    print('Factorial =', factorial(n))
elif ch == 2:
    print(n, 'is prime' if is_prime(n) else 'is not prime')
else:
    print(fibonacci(n))
1.Factorial 2.Prime 3.Fibonacci : 3 Enter n: 10 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Text files

Python
# 2. Create a text file, then count vowels, consonants, uppercase, lowercase
with open('story.txt', 'w') as f:
    f.write('Python Is Easy.\nPractice Daily And Enjoy Coding!\nWe Love It.\n')
v = c = up = lo = 0
with open('story.txt') as f:
    for ch in f.read():
        if ch.isalpha():
            if ch.lower() in 'aeiou': v += 1
            else: c += 1
            if ch.isupper(): up += 1
            else: lo += 1
print('Vowels:', v, 'Consonants:', c, 'Upper:', up, 'Lower:', lo)
Vowels: 18 Consonants: 29 Upper: 11 Lower: 36
Python
# 3. Read a text file line by line and display each word separated by '#'
with open('story.txt') as f:
    for line in f:
        print('#'.join(line.split()))
Python#Is#Easy. Practice#Daily#And#Enjoy#Coding! We#Love#It.
Python
# 4. Copy lines that do NOT contain 'a' into another file
with open('story.txt') as src, open('no_a.txt', 'w') as dst:
    for line in src:
        if 'a' not in line.lower():
            dst.write(line)
with open('no_a.txt') as f:
    print('No a  :', f.read(), end='')
with open('story.txt') as src, open('with_a.txt', 'w') as dst:
    dst.writelines(l for l in src if 'a' in l.lower())
with open('with_a.txt') as f:
    print('With a:', f.read(), end='')
No a : We Love It. With a: Python Is Easy. Practice Daily And Enjoy Coding!

Binary files

Python
# 5. Binary file: store [roll, name] records and search by roll number
import pickle
with open('stud.dat', 'wb') as f:
    for rec in [[1, 'Asha'], [2, 'Ravi'], [3, 'Neha']]:
        pickle.dump(rec, f)
def search(roll):
    with open('stud.dat', 'rb') as f:
        try:
            while True:
                r = pickle.load(f)
                if r[0] == roll:
                    return r[1]
        except EOFError:
            return 'Roll number not found'
print(search(2))
print(search(9))
Ravi Roll number not found
Python
# 6. Binary file: update marks of a given roll number
import pickle
with open('marks.dat', 'wb') as f:
    pickle.dump([[1, 'Asha', 81], [2, 'Ravi', 67], [3, 'Neha', 74]], f)
def update(roll, new):
    with open('marks.dat', 'rb') as f:
        data = pickle.load(f)
    found = False
    for r in data:
        if r[0] == roll:
            r[2] = new; found = True
    with open('marks.dat', 'wb') as f:
        pickle.dump(data, f)
    return found
print('Updated:', update(2, 72))
with open('marks.dat', 'rb') as f:
    print(pickle.load(f))
Updated: True [[1, 'Asha', 81], [2, 'Ravi', 72], [3, 'Neha', 74]]

Random module

Python
# 7. Random number generator that simulates a dice
import random
random.seed(7)                      # same output every run (for the practical file)
rolls = [random.randint(1, 6) for _ in range(10)]
print('Rolls:', rolls)
print('Sixes:', rolls.count(6))
Rolls: [3, 2, 4, 6, 1, 1, 5, 1, 3, 5] Sixes: 1

CSV file

Python
# 8. CSV file: store user-id and password, then search a user-id
import csv
with open('users.csv', 'w', newline='') as f:
    w = csv.writer(f)
    w.writerow(['UserID', 'Password'])
    w.writerows([['asha01', 'Sun@123'], ['ravi_k', 'Moon#45'], ['neha.s', 'Star$78']])
def get_password(uid):
    with open('users.csv', newline='') as f:
        r = csv.reader(f); next(r)
        for u, p in r:
            if u == uid:
                return p
    return 'User not found'
print(get_password('ravi_k'))
print(get_password('zoya'))
Moon#45 User not found

Stack

Python
# 9. Stack implementation using a list (push, pop, peek, display)
stack = []
def push(x): stack.append(x)
def pop(): return stack.pop() if stack else 'Underflow'
def peek(): return stack[-1] if stack else 'Underflow'
for x in [10, 20, 30]:
    push(x)
print('Stack (top first):', stack[::-1])
print('Peek:', peek(), '| Pop:', pop(), '| Now:', stack)
print(pop(), pop(), pop())
Stack (top first): [30, 20, 10] Peek: 30 | Pop: 30 | Now: [10, 20] 20 10 Underflow

Sorting & searching

Python
# 10. Bubble sort and binary search on a list of numbers
def bubble(a):
    for i in range(len(a) - 1):
        for j in range(len(a) - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
    return a
def bsearch(a, key):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == key: return mid
        if a[mid] < key: lo = mid + 1
        else: hi = mid - 1
    return -1
nums = bubble([34, 7, 23, 32, 5, 62])
print('Sorted:', nums)
print('23 at index', bsearch(nums, 23))
Sorted: [5, 7, 23, 32, 34, 62] 23 at index 2

Dictionary + file

Python
# 11. Count occurrences of each word in a text file using a dictionary
with open('para.txt', 'w') as f:
    f.write('the cat and the hat and the bat')
freq = {}
with open('para.txt') as f:
    for w in f.read().split():
        freq[w] = freq.get(w, 0) + 1
for w in sorted(freq, key=freq.get, reverse=True):
    print(w, freq[w])
the 3 and 2 cat 1 hat 1 bat 1

Exception handling

Python
# 12. Exception handling while dividing user values
try:
    a = int(input('a: '))
    b = int(input('b: '))
    print('a / b =', a / b)
except ZeroDivisionError:
    print('Cannot divide by zero')
except ValueError:
    print('Please enter whole numbers only')
finally:
    print('Program over')
a: 25 b: 0 Cannot divide by zero Program over

Python–MySQL programs

The four connectivity programs (create table, insert, fetch, update/delete) with output are in the Python–MySQL Connectivity lesson, and the SQL query sets are in SQL DDL & DML, GROUP BY and Joins.

Download all programs

The ZIP contains every program of this course as a .py file with its output written as comments, plus the SQL files.

⬇ Download class-12-cs-practical-programs

Frequently Asked Questions

How many programs should a Class 12 CS practical file have?
Usually 15–20 Python programs and about 5 sets of SQL queries, including file handling, stack and Python–MySQL connectivity, as directed by your teacher.
Why is random.seed() used in program 7?
It fixes the sequence of random numbers so that the output written in the file matches every run. Without it, each run gives different numbers.
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicImportant Questions & Viva Your progress: 25 / 26 (96%) · Lesson 26 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free