Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🏆 Revision और Practice  ·  Lesson 25

ज़रूरी Programs (Practical File)

Programs की list

ये programs practical file की आम list के अनुसार हैं। हर program पूरा और tested है; दिखाया गया output असली output है। एक program की बनाई files (story.txt) अगले programs इस्तेमाल करते हैं, इसलिए इन्हें क्रम से चलाएँ।

🧮
FunctionsProgram 1
📄
Text filesPrograms 2–4, 11
💾
Binary filesPrograms 5–6
🎲
RandomProgram 7
📊
CSVProgram 8
📚
StackProgram 9
🔎
Sort/SearchProgram 10
🛢️
MySQLConnectivity lesson
क्या-क्या शामिल है

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

चारों connectivity programs (table बनाना, insert, fetch, update/delete) output के साथ Python–MySQL Connectivity lesson में हैं, और SQL query sets SQL DDL & DML, GROUP BY और Joins में।

सभी programs download करें

ZIP में इस course का हर program .py file के रूप में है, output comments में लिखा है, साथ में SQL files भी।

⬇ Download class-12-cs-practical-programs

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Class 12 CS practical file में कितने programs होने चाहिए?
आमतौर पर 15–20 Python programs और लगभग 5 sets SQL queries, जिनमें file handling, stack और Python–MySQL connectivity हों, teacher के निर्देश के अनुसार।
Program 7 में random.seed() क्यों है?
यह random numbers का क्रम तय कर देता है ताकि file में लिखा output हर बार चलाने पर मेल खाए। इसके बिना हर बार अलग numbers आते हैं।
← Class 12 Computer Science
🔗

Share this topic with a friend

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

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

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

अगला topicज़रूरी Questions और Viva आपकी प्रगति: 25 / 26 (96%) · Lesson 26 / 26 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें