PYTHON PRACTICE PROGRAMS
Class 12 • File Handling • Random • Stack
1. Generate three random numbers between 3 and 10.
import random
def generate_numbers():
for i in range(3):
print([Link](3, 10))
generate_numbers()
2. Generate a six-digit OTP.
import random
def generate_otp():
return [Link](100000, 999999)
print("Your OTP is:", generate_otp())
3. Count uppercase and lowercase letters in a TXT file.
upper = lower = 0
with open("[Link]", "r") as file:
text = [Link]()
for ch in text:
if [Link](): upper += 1
elif [Link](): lower += 1
print("Uppercase:", upper)
print("Lowercase:", lower)
4. Copy the content of one text file into another.
with open("[Link]", "r") as f1:
content = [Link]()
with open("[Link]", "w") as f2:
[Link](content)
print("Content copied successfully.")
5. Insert Student ID, Student Name and Student Address in a binary file.
import pickle
sid = int(input("Enter Student ID: "))
sname = input("Enter Student Name: ")
saddress = input("Enter Student Address: ")
with open("[Link]", "ab") as file:
[Link]([sid, sname, saddress], file)
print("Student details inserted successfully.")
6. Display all records of [Link] file.
import pickle
with open("[Link]", "rb") as file:
while True:
try:
record = [Link](file)
print(record)
except EOFError:
break
7. Insert FID, FPrice and FName in a furniture binary file.
import pickle
fid = int(input("Enter Furniture ID: "))
fprice = float(input("Enter Furniture Price: "))
fname = input("Enter Furniture Name: ")
with open("[Link]", "ab") as file:
[Link]([fid, fprice, fname], file)
print("Furniture details inserted successfully.")
8. Search and display [Link] records whose price is greater than 10,000.
import csv
def search_furniture():
with open("[Link]", "r") as file:
data = [Link](file)
for record in data:
if float(record[1]) > 10000:
print(record)
search_furniture()
9. Count the words 'you' and 'me' from [Link].
def count_words():
count_you = count_me = 0
with open("[Link]", "r") as file:
text = [Link]().lower().split()
for word in text:
if word == "you": count_you += 1
elif word == "me": count_me += 1
print("Number of 'you':", count_you)
print("Number of 'me':", count_me)
count_words()
10. Perform all basic stack operations.
stack = []
def push():
[Link](input("Enter element to push: "))
def pop():
if stack: print("Deleted:", [Link]())
else: print("Stack Underflow")
def peek():
if stack: print("Top element:", stack[-1])
else: print("Stack is empty")
def display():
print("Stack:", stack[::-1] if stack else "Stack is empty")
while True:
print("\[Link] [Link] [Link] [Link] [Link]")
ch = int(input("Enter choice: "))
if ch == 1: push()
elif ch == 2: pop()
elif ch == 3: peek()
elif ch == 4: display()
elif ch == 5: break
else: print("Invalid choice")