SECTION 1: PYTHON PROGRAMMING
1. Read a text file line by line and display each word separated by a #
“We open a file, read every line, break it into words, and join them with
# like friends holding hands.”
# Program 1: Read a text file line by line and display each word
separated by #
# Open the file in read mode
file = open("[Link]", "r")
# Read each line one by one
for line in file:
# Split line into words
words = [Link]()
# Join words using '#' and print
print('#'.join(words))
# Close the file
[Link]()
Explanation:
.split() breaks a line into words.
'#'.join(words) glues them back with #.
Loop ensures we read line by line.
2. Read a text file and display number of vowels, consonants,
uppercase, lowercase characters
“We count how many A, E, I, O, U and how many big and small
letters are dancing in the file.”
# Program 2: Count vowels, consonants, uppercase, lowercase
characters
vowels = 'aeiouAEIOU'
vowel_count = consonant_count = upper_count = lower_count = 0
with open("[Link]", "r") as file:
for line in file:
for ch in line:
if [Link]():
if ch in vowels:
vowel_count += 1
else:
consonant_count += 1
if [Link]():
upper_count += 1
elif [Link]():
lower_count += 1
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
print("Uppercase letters:", upper_count)
print("Lowercase letters:", lower_count)
Explanation:
.isalpha() checks if it’s a letter.
.isupper() and .islower() check letter case.
We simply count as we go.
3. Remove all lines containing the letter 'a' and write them to
another file
“We look for lines with ‘a’ and put them in a new home (new
file).”
# Program 3: Remove all lines containing 'a' and write them to another
file
with open("[Link]", "r") as file:
lines = [Link]()
with open("[Link]", "w") as outfile:
for line in lines:
if 'a' not in line:
[Link](line)
print("Lines without 'a' have been written to [Link]")
Explanation:
Reads all lines first.
Writes only those that don’t contain 'a'.
4. Create a binary file with name and roll number. Search for
roll number and display details
“We put students’ name and roll in a magic box (binary file).
Then we open the box and find who’s there.”
# Program 4: Binary file with name and roll number
import pickle # used for binary file handling
# Data entry
records = []
for i in range(3):
name = input("Enter name: ")
roll = int(input("Enter roll number: "))
[Link]({'name': name, 'roll': roll})
# Write data to binary file
with open("[Link]", "wb") as file:
[Link](records, file)
# Search part
roll_search = int(input("Enter roll number to search: "))
found = False
with open("[Link]", "rb") as file:
data = [Link](file)
for rec in data:
if rec['roll'] == roll_search:
print("Name:", rec['name'])
found = True
if not found:
print("Roll number not found.")
Explanation:
pickle helps us store Python objects in binary format.
We store a list of dictionaries.
Later, we search for a specific roll number.
5. Create binary file with roll, name, marks. Input roll, update
marks
“We look up a student by roll number and change their marks—
like fixing a report card!”
# Program 5: Update marks in a binary file
import pickle
# Step 1: Create and save data
students = [
{"roll": 1, "name": "Amit", "marks": 80},
{"roll": 2, "name": "Ravi", "marks": 90},
{"roll": 3, "name": "Sita", "marks": 85}
with open("[Link]", "wb") as f:
[Link](students, f)
# Step 2: Update marks
roll_search = int(input("Enter roll number to update marks: "))
new_marks = int(input("Enter new marks: "))
with open("[Link]", "rb") as f:
data = [Link](f)
for student in data:
if student["roll"] == roll_search:
student["marks"] = new_marks
print("Marks updated!")
# Step 3: Save again
with open("[Link]", "wb") as f:
[Link](data, f)
Explanation:
We open the file, read data, modify it, and save it again.
It’s like editing a notebook entry.
6. Write a random number generator (1 to 6) — Dice Simulation
“We roll an invisible dice and print what number comes up.”
# Program 6: Dice Simulation
import random
# Generate random number between 1 and 6
dice = [Link](1, 6)
print("Dice shows:", dice)
Explanation:
[Link](1,6) picks any number between 1 and 6 like a dice
roll.
7. Implement a stack using list
“A stack is like a lunchbox — last thing you put in, comes out
first.”
# Program 7: Stack using list
stack = []
def push():
element = input("Enter element to push: ")
[Link](element)
print("Stack:", stack)
def pop():
if not stack:
print("Stack is empty!")
else:
print("Popped element:", [Link]())
def display():
print("Current Stack:", stack)
while True:
print("\[Link] [Link] [Link] [Link]")
choice = int(input("Enter choice: "))
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
break
Explanation:
append() = push
pop() = remove last
Stack works on LIFO (Last In, First Out).
8. Create a CSV file with user-id and password, then read &
search
“We save user details in a table (CSV), and later find their
password.”
# Program 8: CSV File - user-id & password
import csv
# Write data to CSV
with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](["userid", "password"])
for i in range(3):
uid = input("Enter user id: ")
pwd = input("Enter password: ")
[Link]([uid, pwd])
# Read and search
search_id = input("Enter user id to search: ")
found = False
with open("[Link]", "r") as file:
reader = [Link](file)
next(reader) # skip header
for row in reader:
if row[0] == search_id:
print("Password:", row[1])
found = True
if not found:
print("User not found!")
Explanation:
[Link] saves user-id/password.
[Link] helps to read it back.
SECTION 2: DATABASE MANAGEMENT
1. Create a student table and perform SQL operations
“We make a table for students and play with it — adding,
changing, sorting, and deleting info.”
Example (using SQLite in Python):
# Program 9: SQL Operations with Python
import sqlite3
# Connect to database (creates file if not exists)
conn = [Link]("[Link]")
cursor = [Link]()
# Create table
[Link]('''
CREATE TABLE IF NOT EXISTS student(
roll INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
''')
# Insert data
[Link]("INSERT INTO student VALUES(1, 'Amit', 85)")
[Link]("INSERT INTO student VALUES(2, 'Ravi', 90)")
[Link]("INSERT INTO student VALUES(3, 'Sita', 75)")
[Link]()
# ALTER example - Add new column
[Link]("ALTER TABLE student ADD COLUMN grade TEXT")
# UPDATE example
[Link]("UPDATE student SET marks = 95 WHERE roll = 2")
# ORDER BY example
for row in [Link]("SELECT * FROM student ORDER BY marks
DESC"):
print(row)
# GROUP BY example (find average marks)
for row in [Link]("SELECT AVG(marks) FROM student"):
print("Average Marks:", row[0])
# DELETE example
[Link]("DELETE FROM student WHERE roll = 3")
[Link]()
[Link]()
print("Database operations completed successfully!")
Explanation:
sqlite3 lets us use SQL inside Python easily.
We use standard SQL commands:
ALTER, UPDATE, ORDER BY, GROUP BY, DELETE.