VVDAV PUBLIC
SCHOOL
COMPUTER SCIENCE
PRACTICAL FILE
BY:- JASMEET SINGH
22 , 12C
➔ 1. Read a text file and display the number of
uppercase/lowercase/vowels/consonants/digits/special characters in
the file.
➔ def count():
f=open("C:\\prac\data.txt","r")
V=C=U=L=D=S=0
data=f.read()
for i in data:
if i.isalpha():
if i.isupper():
U+=1
elif i.islower:
L+=1
elif i.lower() in "aeiou":
V+=1
else:
C+=1
else:
if i.isdigit():
D+=1
else:
S+=1
print("Number of uppercase letters: ",U)
print("Number of lowercase letters: ",L)
print("Number of vowels: ",V)
print("Number of consonants: ",C)
print("Number of digits: ",D)
print("Number of special characters: ",S)
f.close()
count()
➔ OUTPUT:-
➔ 2. Remove all the lines that contain the character 'a' in a file and
write it to another file.
➔ def remove():
f=open("C:\\test\data_old.txt","r")
lines=f.readlines()
fo=open("C:\\test\data_old.txt","w")
fn=open("C:\\test\data_new.txt","w")
for line in lines:
if 'a' in line:
fn.write(line)
else:
fo.write(line)
print("Data updated")
remove()
➔ OUTPUT:-
➔ 3. Create a binary file with roll number, name and marks. Input a roll
number and update the marks.
➔ import pickle
def write():
f=open("C:\\test\student.dat","wb")
while True:
r=int(input("Enter roll no. : "))
n=input("Enter name : ")
m=int(input("Enter marks : "))
record=[r,n,m]
pickle.dump(record,f)
ch=input("Do you want to add more values? (Y/N)")
if ch in 'nN':
break
f.close()
def read():
f=open("C:\\test\student.dat","rb")
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def update():
f=open("C:\\test\student.dat","rb+")
rollno=int(input("Enter the roll no. for which you want to update the marks : "))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
um=int(input("Enter updated marks : "))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
except EOFError:
f.close()
write()
read()
update()
read()
➔ OUTPUT:-
➔ 4. Create a binary file to enter records, display records and search
for a record.
➔ import pickle
def add_employee():
with open("employees.dat", "ab") as file:
emp_id = int(input("Enter Employee ID: "))
name = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
date_of_joining = input("Enter Date of Joining (DD-MM-YYYY): ")
employee = {
'ID': emp_id,
'Name': name,
'Salary': salary,
'Date of Joining': date_of_joining
}
pickle.dump(employee, file)
print("Employee record added successfully!\n")
def display_employees():
try:
with open("employees.dat", "rb") as file:
print("Displaying all employee records:")
while True:
try:
employee = pickle.load(file)
print(employee)
except EOFError:
break
except FileNotFoundError:
print("File not found. Please add records first.\n")
def search_employee():
emp_id = int(input("Enter Employee ID to search: "))
found = False
try:
with open("employees.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee['ID'] == emp_id:
print("Employee record found:", employee)
found = True
break
except EOFError:
break
if not found:
print("Employee record not found.\n")
except FileNotFoundError:
print("File not found. Please add records first.\n")
def main():
while True:
print("Menu:")
print("1. Add Employee Record")
print("2. Display All Records")
print("3. Search for an Employee Record")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
add_employee()
elif choice == '2':
display_employees()
elif choice == '3':
search_employee()
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.\n")
main()
➔ OUTPUT:-
➔ 5. Create a CSV file by entering user-id and password, read and
search the password for given user-id.
➔ import csv
def write():
try:
with open("C:\\test\\sigma.csv", "a", newline='') as f:
wo = csv.writer(f)
f.seek(0)
if f.tell() == 0:
wo.writerow(["UserId", "Password"])
while True:
u_id = input("Enter the User ID: ")
pswd = input("Enter Password: ")
data = [u_id, pswd]
wo.writerow(data)
ch = input("Do you want to enter more? (Y/N): ")
if ch in 'Nn':
break
except Exception as e:
print(f"Error: {e}")
def read():
try:
with open("C:\\test\\sigma.csv", "r") as f:
ro = csv.reader(f)
for i in ro:
print(i)
except FileNotFoundError:
print("File not found. Please write records first.")
def search():
try:
with open("C:\\test\\sigma.csv", "r") as f:
u = input("Enter User ID to search: ")
ro = csv.reader(f)
next(ro)
for i in ro:
if i[0] == u:
print("Password:", i[1])
return
print("User ID not found.")
except FileNotFoundError:
print("File not found. Please write records first.")
write()
read()
search()
➔ OUTPUT:-
➔ 6. MAKE A PYTHON PROGRAM FOR MANAGING BOOK INVENTORY
WITH CSV FILE:
➔ import csv
def write_data():
with open("books.csv", mode='a', newline='') as file:
writer = csv.writer(file)
if file.tell() == 0:
writer.writerow(["Book ID", "Title", "Author", "Price"])
while True:
book_id = input("Enter Book ID: ")
title = input("Enter Book Title: ")
author = input("Enter Author Name: ")
price = input("Enter Price: ")
writer.writerow([book_id, title, author, price])
more = input("Do you want to enter another book? (Y/N): ")
if more.lower() != 'y':
break
def read_data():
try:
with open("books.csv", mode='r') as file:
reader = csv.reader(file)
next(reader)
print("\nBook Inventory Records:")
for row in reader:
print(f"Book ID: {row[0]}, Title: {row[1]}, Author: {row[2]}, Price:
{row[3]}")
except FileNotFoundError:
print("The file does not exist. Please add book records first.")
def search_data():
book_id = input("Enter the Book ID to search: ")
found = False
try:
with open("books.csv", mode='r') as file:
reader = csv.reader(file)
next(reader)
for row in reader:
if row[0] == book_id:
print(f"Book Found: ID = {row[0]}, Title = {row[1]}, Author = {row[2]},
Price = {row[3]}")
found = True
break
if not found:
print("Book ID not found.")
except FileNotFoundError:
print("The file does not exist. Please add book records first.")
def main():
while True:
print("\nMenu:")
print("1. Add Book Details")
print("2. View All Book Records")
print("3. Search for a Book by ID")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
write_data()
elif choice == '2':
read_data()
elif choice == '3':
search_data()
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
➔ OUTPUT:-
➔ 7. Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
➔ import random
while True:
print("="*69)
print("*"*25,"ROLLING THE DICE","*"*25)
print("="*69)
num=random.randint(1,6)
if num==6:
print("YOOO YOU GOT",num,"GGZ")
elif num==1:
print("Oh nah imagine getting",num)
else:
print("Cool you got",num)
ch=input("Roll again? (Y/N):")
if ch in 'Nn':
break
print("*"*25,"THANKS FOR PLAYING","*"*25)
➔ OUTPUT:-
➔ 8. WRITE A PROGRAM TO SHOW IF THE ENTERED STRING IS
PALINDROME OR NOT.
➔ def is_palindrome(s):
cleaned_string = ""
for char in s:
if char != " ":
cleaned_string += char.lower()
return cleaned_string == cleaned_string[::-1]
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")
➔ OUTPUT:-
➔ 9. WRITE A PROGRAM TO FIND AND DISPLAY THE SUM OF ALL
VALUES WHICH ARE ENDING WITH n FROM A LIST.
➔ def sum_values_ending_with_n(n, values):
total = 0
for value in values:
if isinstance(value, int) or (isinstance(value, str) and value.isdigit()):
value = int(value)
if value % 10 == n:
total += value
return total
n = int(input("Enter the digit (n) to check for numbers ending with it: "))
values = input("Enter a list of numbers separated by spaces: ").split()
values = [int(x) if x.isdigit() else x for x in values]
result = sum_values_ending_with_n(n, values)
print(f"The sum of numbers ending with {n} is: {result}")
➔ OUTPUT:-
➔ 10. WRITE A PROGRAM TO REMOVE ALL ODD/EVEN NUMBERS FROM
A GIVEN LIST.
➔ def remove_numbers(choice, numbers):
if choice == "odd":
return [num for num in numbers if num % 2 == 0]
elif choice == "even":
return [num for num in numbers if num % 2 != 0]
else:
return numbers
while True:
numbers = list(map(int, input("Enter a list of numbers separated by spaces:
").split()))
choice = input("Do you want to remove 'odd' or 'even' numbers? ").strip().lower()
filtered_numbers = remove_numbers(choice, numbers)
print(f"The updated list after removing {choice} numbers: {filtered_numbers}")
again = input("Do you want to perform the operation again? (Y/N):
").strip().lower()
if again in 'Nn':
print("Goodbye!")
break
➔ OUTPUT:-
➔ 11. WRITE A PROGRAM TO CREATE DIFFERENT TYPE OF PATTERNS
ACCORDING TO USER’S INPUT.
➔ def print_pattern(pattern_type, rows):
if pattern_type == 1:
#Right-Angled Triangle
for i in range(1, rows + 1):
print('*' * i)
elif pattern_type == 2:
#Inverted Right-Angled Triangle
for i in range(rows, 0, -1):
print('*' * i)
elif pattern_type == 3:
#Pyramid Pattern
for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
elif pattern_type == 4:
#Inverted Pyramid Pattern
for i in range(rows, 0, -1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
elif pattern_type == 5:
#Square Pattern
for i in range(rows):
print('*' * rows)
elif pattern_type == 6:
#Hollow Square Pattern
for i in range(rows):
if i == 0 or i == rows - 1:
print('*' * rows)
else:
print('*' + ' ' * (rows - 2) + '*')
elif pattern_type == 7:
#Number Pyramid
num = 1
for i in range(1, rows + 1):
print(' ' * (rows - i) + ''.join(str(num + j) for j in range(i)))
num += i
elif pattern_type == 8:
#Reverse Number Pyramid
num = rows * (rows + 1) // 2
for i in range(rows, 0, -1):
print(' ' * (rows - i) + ''.join(str(num - j) for j in range(i)))
num -= i
else:
print("Invalid pattern type selected.")
def main():
print("Pattern Types:")
print("1. Right-Angled Triangle")
print("2. Inverted Right-Angled Triangle")
print("3. Pyramid")
print("4. Inverted Pyramid")
print("5. Square (Filled with stars)")
print("6. Hollow Square")
print("7. Number Pyramid")
print("8. Reverse Number Pyramid")
pattern_type = int(input("Enter pattern type (1-8): "))
rows = int(input("Enter number of rows: "))
print("\nPattern Output:")
print_pattern(pattern_type, rows)
if __name__ == "__main__":
main()
➔ OUTPUT:-
➔ 12. WRITE A PROGRAM TO FIND THE NUMBER OF TIMES A
CHARACTER IS USED IN A GIVEN STRING.
➔ str = input("Enter the string: ")
choice = input("Enter the letter to be searched: ")
x=0
for i in str:
if i == choice:
count += 1
print("Number of times character",ch,"occurs in the string is:",count)
➔ OUTPUT:-
➔ 13. WAP to find whether the number entered is an armstrong
number or not.
➔ num=int(input("Enter a 3 digit number:"))
s=0
temp=num
while (temp>0):
digit=temp%10
s+=digit**3
temp//=10
if (num==s):
print(num,"is an armstrong number")
else:
print(num,"is not an armstrong number")
➔ OUTPUT:-
➔ 14. Write a program to reverse string using stacks.
➔ class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
return None
def is_empty(self):
return len(self.stack) == 0
def reverse_string(input_string):
stack = Stack()
for char in input_string:
stack.push(char)
reversed_string = ''
while not stack.is_empty():
reversed_string += stack.pop()
return reversed_string
if __name__ == "__main__":
original_string = input("Enter a string to reverse: ")
reversed_result = reverse_string(original_string)
print("Original String:", original_string)
print("Reversed String:", reversed_result)
➔ OUTPUT:-
➔ 15. Write functions AddPlayer(player) and DeletePlayer(player)
in python to add and remove a player by considering them as
push and pop operations in a stack.
➔ class PlayerStack:
def __init__(self):
self.stack = []
def AddPlayer(self, player):
self.stack.append(player)
print(f'Player "{player}" has been added to the stack.')
def DeletePlayer(self):
if not self.is_empty():
removed_player = self.stack.pop()
print(f'Player "{removed_player}" has been removed from the
stack.')
else:
print("The stack is empty. No players to remove.")
def is_empty(self):
return len(self.stack) == 0
def display_stack(self):
if not self.is_empty():
print("Current players in the stack:", self.stack)
else:
print("The stack is empty.")
# Example Usage
if __name__ == "__main__":
player_stack = PlayerStack()
while True:
print("\n=== Player Stack Operations ===")
print("1. Add Player")
print("2. Delete Player")
print("3. Display Stack")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
player = input("Enter the player's name to add: ")
player_stack.AddPlayer(player)
elif choice == '2':
player_stack.DeletePlayer()
elif choice == '3':
player_stack.display_stack()
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
➔ OUTPUT:-
➔ 16. CREATE A TABLE: LIBRARY.
➔ 17. INSERT DATA INTO THE TABLE.
➔ 18. RETRIEVE ALL BOOKS FROM THE LIBRARY.
➔ 19. FIND BOOKS BY AUTHOR.
➔ 20. UPDATE THE NUMBER OF COPIES AVAILABLE.
➔ 21. DELETE A BOOK FROM THE LIBRARY.
➔ 22. FIND BOOKS PUBLISHED AFTER A CERTAIN YEAR.
➔ 23. COUNT THE NUMBER OF BOOKS IN EACH GENRE.
➔ 24. FIND BOOKS WITH A SPECIFIC GENRE AND AVAILABLE
COPIES GREATER THAN A CERTAIN NUMBER.
➔ 25. SORT BOOKS BY YEAR OF PUBLICATION(DESCENDING).
➔ 26. FIND BOOKS WITH SPECIFIC KEYWORDS IN TITLE.
➔ 27. RETRIEVE THE BOOK WITH HIGHEST NUMBER OF
AVAILABLE COPIES.
➔ 28. RETRIEVE BOOKS THAT ARE AVAILABLE FOR BORROWING
(MORE THAN 0 COPIES AVAILABLE).
➔ 29. FIND THE TOTAL NUMBER OF COPIES OF ALL BOOKS.
➔ 30. ADD A NEW COLUMN FOR BOOK PRICE.