Computer Science Practical Programs
Computer Science Practical Programs
'''
1. Write an interactive menu driven program in Python using
functions to traverse and search for the student name from a list of
students containing student roll number, name and average.
'''
'''
def Search(l, n):
temp = 0
length = len(l)
for i in range(length):
for j in range(3):
if l[i][j] == n:
temp = i
print(l[temp])
break
student_list = []
rep = 'y'
while rep == 'y':
s_rno = int(input("Enter the Student's Roll no: "))
s_name = input("Enter the Student's Name: ")
s_avg = float(input("Enter the Student's Average: "))
t = [s_rno, s_name, s_avg]
student_list.append(t)
rep = input("Continue? (y/n): ")
rep = 'y'
while rep == 'y':
search = eval(input("Enter the Student's Details you want to search: "))
Search(student_list, search)
rep = input("Continue? (y/n): ")
'''
'''
def ReplaceHalves(l):
length = len(l)
m = len(l) // 2
if length % 2 == 0:
l = l[m:] + l[:m]
print("List after exchange: ", l)
else:
l = l[m + 1:] + [l[m]] + l[:m]
print("List after exchange: ", l)
def isPalindrome(l):
ct = 0
length = len(l)
for i in range(length):
if l[i][::-1] == l[i]:
ct = ct + 1
print("Number of Palindromes in the given list (%s): " % (l), ct)
rep = 'y'
while rep == 'y':
print()
print("1. Exchange Halves")
print("2. Palindrome words")
print()
choice = int(input("Enter your choice: "))
if choice == 1:
h_list = list(eval((input("Enter a list of elements: "))))
ReplaceHalves(h_list)
rep = input("Continue? (y/n): ")
elif choice == 2:
p_list = list(eval(input("Enter a list of strings: ")))
isPalindrome(p_list)
rep = input("Continue? (y/n): ")
else:
print("Invalid choice. Please try again.")
'''
'''
def Boundary(l, m, n):
sum = 0
for i in range(m): # 0
for j in range(n): #2
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
sum += l[i][j]
return sum
l = []
m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))
for i in range(m):
t = []
for j in range(n):
no = int(input("Enter the number: "))
t.append(no)
l.append(t)
print(l)
'''4. Consider the following tables WORKER and PAYLEVEL and answer
the questions that follows:
Write SQL commands for the following statements:
(i) To display the details of all the WORKERS in descending order of
their DOJ.
(ii) To display the NAME and DESIG of those WORKERS whose
PLEVEL is either P001 or P002.
(iii) To display the number of workers whose PAY+ALLOWANCE is
more than 30000 for every PLEVEL.
(iv) To increase the ALLOWANCE by 1000 where the pay is greater
than 20000.
(v) To display the number of Workers designation wise.
'''
'''
import mysql.connector as spc
co = spc.connect(host='localhost', user='toor', passwd='',
database='JothishKamal')
cu = co.cursor()
# Inserting Records
cu.execute("insert into Worker values(11, 'RadheShyam', 'Supervisor',
'P001', '2004-09-12', '1981-08-23')")
cu.execute("insert into Worker values(12, 'Chandernath', 'Operator',
'P003', '2010-02-22', '1987-07-12')")
cu.execute("insert into Worker values(13, 'Fizza', 'Operator', 'P003', '2009-
06-14', '1983-10-14')")
cu.execute("insert into Worker values(14, 'Ameen Ahmad', 'Mechanic',
'P002', '2006-08-21', '1984-03-13')")
cu.execute("insert into Worker values(15, 'Sanya', 'Clerk', 'P002', '2005-
12-19', '1983-06-09')")
cu.execute("insert into Worker values(18, 'Sarsa', 'Supervisor', 'P001',
'2010-01-20', '1982-02-01')")
co.commit()
# (i) To display the details of all the WORKERS in descending order of their
DOJ.
print()
print("(i)")
print()
for i in data:
print(i)
# (ii) To display the NAME and DESIG of those WORKERS whose PLEVEL is
either P001 or P002.
print()
print("(ii)")
print()
for i in data:
print(i)
print()
print("(iii)")
print()
for i in data:
print(i)
# (iv) To increase the ALLOWANCE by 1000 where the pay is greater than
20000
print()
print("(iv)")
print()
cu.execute("UPDATE PAYLEVEL SET ALLOWANCE = ALLOWANCE+1000
WHERE PAY>20000;")
co.commit()
cu.execute("SELECT * FROM PAYLEVEL WHERE PAY > 20000")
data = cu.fetchall()
print(data)
print()
print("(v)")
print()
for i in data:
print(i)
'''
'''5. Consider the following tables SPORTS and COACH and answer the
questions that follows:
Write SQL commands for the following statements:
(i) To display scode, the number of coaches for each scode from the
table coach and display scode in descending order.
(ii) To display details of those sports and coachname which are
having Prizemoney more than 9000 and coachname ends with ‘n’.
(iii) To display the contents of the sports table with their coachname
whose schedule date is in the year 2019.
(iv) To display number of different participants from the table sports.
(v) Increase the Participants by 6 for the sports carom, chess and
badminton.
'''
'''
import mysql.connector as spc
# Creating Tables
# Inserting Records
co.commit()
# (i) To display scode, the number of coaches for each scode from the
table coach and display scode in descending order.
print()
print("(i)")
print()
for i in data:
print(i)
# (ii) To display details of those sports and coachname which are having
Prizemoney more than 9000 and coachname ends with ‘n’.
cu.execute("SELECT SPORTSNAME, NAME 'COACHNAME' FROM SPORTS,
COACH WHERE SPORTS.SCODE=COACH.SCODE AND PRIZEMONEY > 9000
AND NAME LIKE '%N';")
data = cu.fetchall()
print()
print("(ii)")
print()
for i in data:
print(i)
# (iii) To display the contents of the sports table with their coachname
whose schedule date is in the year 2019.
print()
print("(iii)")
print()
for i in data:
print("EMPTY TABLE")
for i in data:
print(i)
# (v) Increase the Participants by 6 for the sports carrom, chess and
badminton.
print()
print("(v)")
print()
for i in data:
print(i)
'''
'''6. Consider the following tables Teacher and Posting answer the
questions that follows:
Write SQL commands for the following statements:
(i) To display the total number of teachers Department wise.
(ii) To display the Teacher details who have been posted in “Delhi”.
(iii) To display the highest salary being paid in each department
(iv) To display the total salary being paid for male and female
separately
(v) Increase the salary for the teachers by 10% who have joined in
the year 2017 and 2018.
'''
'''
import mysql.connector as spc
# Creating Tables
# Inserting records
for i in range(num2):
pid = int(input("Enter Posting ID: "))
dep = input("Enter Department: ")
place = input("Enter Place: ")
query = "insert into Posting values(%s, '%s', '%s')" % (pid, dep, place)
cu.execute(query)
co.commit()
print()
print("(i)")
print()
for i in data:
print(i)
# (ii) To display the Teacher details who have been posted in “Delhi”.
print()
print("(ii)")
print()
for i in data:
print(i)
print()
print("(iii)")
print()
for i in data:
print(i)
# (iv) To display the total salary being paid for male and female
separately.
print()
print("(iv)")
print()
for i in data:
print(i)
# (v) To increase the salary for the teachers by 10% who have joined in
the year 2017 and 2018.
print()
print("(v)")
print()
for i in data:
print(i)
'''
'''
7. Write a program to connect Python with MySQL using database
connectivity and perform the following operations on data in database:
Insert, Fetch, Update and Delete the data.
(i) Create a table Student with admno, sname, gender, dob, stream,
average.
(ii) Insert 5 records into the student table by accepting from the
user.
(iii) Increase the marks by 5 for those students who belong to science
stream.
(iv) Display the number of male students who belong to commerce
stream.
(v) Delete the records of those students whose average<40.
'''
'''
import mysql.connector as spc
co = spc.connect(host='localhost', user='toor', passwd='',
database='JothishKamal')
cu = co.cursor()
# (i) Create a table Student with admno, sname, gender, dob, stream,
average.
# (ii) Insert 5 records into the student table by accepting from the user.
for i in range(5):
admno = int(input("Enter Student's Admn No: "))
name = input("Enter Student's Name: ")
gen = input("Enter Student's Gender: ")
dob = input("Enter Student's DOB: ")
stream = input("Enter Student's Stream: ")
avg = float(input("Enter Student's Average: "))
query = "insert into Student values(%s, '%s', '%s', '%s', '%s', %s)" %
(admno, name, gen, dob , stream, avg)
cu.execute(query)
co.commit()
# (iii) Increase the marks by 5 for those students who belong to science
stream.
print()
print("(iii)")
print()
for i in data:
print(i)
# (iv) Display the number of male students who belong to commerce
stream.
print()
print("(iv)")
print()
for i in data:
print(i)
for i in data:
print("Deleted Record: ", i)
'''
'''
8. Write a program to connect Python with MySQL using database
connectivity and perform the following operations on data in database:
Fetch, Update and Delete the data.
(i) Create 2 tables
● Table name - Event with EventId, Eventname, NumPerformers,
CelebrityID.
● Table name – Celebrity with CelebrityID, Name, Phone,
FeeCharged
(ii) Insert 5 records in both the tables
(iii) Display the Eventname, Name of celebrity and Feecharged for
those celebrities who charge more than 200000
(iv) Increase the Feecharged by 10,000 for the events whose number
of Performers is > 15
(v) Delete the records of those Celebrity whose name starts with R
'''
'''
import mysql.connector as spc
co = spc.connect(host='localhost', user='toor', passwd='',
database='JothishKamal')
cu = co.cursor()
co.commit()
# (iii) Display the Eventname, Name of celebrity and Feecharged for those
celebrities who charge more than 200000
print()
print("(iii)")
print()
for i in data:
print(i)
# (iv) Increase the Feecharged by 10,000 for the events whose number of
Performers is > 15
print()
print("(iv)")
print()
for i in data:
print(i)
# (v) Delete the records of those Celebrity whose name starts with R.
print()
print("(v)")
print()
for i in data:
print(i)
'''
'''
9. Write a program to connect Python with MySQL using database
connectivity and perform the following operations on data in database:
Fetch, Update and Delete the data.
(i) Create 2 tables
● Table name - Employee with Empno, Name, Desig, Salary,
Leave, Bonus.
● Table name – Insurance with Empno, LIC
(ii) Insert 5 records in both the tables by accepting the values of the
attributes from the user.
(iii) Display the total salary of each designation of those employees
whose name starts with ‘R’.
(iv) Display the Employee Number and Name who has the LIC
insurance.
(v) Update the salary by 10% for those employees whose designation
is Clerk.
'''
'''
import mysql.connector as spc
co = spc.connect(host='localhost', user='toor', passwd='',
database='JothishKamal')
cu = co.cursor()
# (ii) Insert 5 records in both the tables by accepting the values of the
attributes from the user.
for i in range(5):
empno = int(input("Enter Employee Number: "))
name = input("Enter Employee's Name: ")
desig = input("Enter Employee's Designation: ")
sal = int(input("Enter Employee's Salary: "))
leaves = int(input("Enter Employee's number of holidays: "))
bonus = int(input("Enter Employee's Bonus: "))
lic = input("Is LIC Insurance covered? (Yes/No): ")
query1 = "insert into Employee values(%s, '%s', '%s', %s, %s, %s)" %
(empno, name, desig, sal, leaves, bonus)
query2 = "insert into Insurance values(%s, '%s')" % (empno, lic)
cu.execute(query1)
cu.execute(query2)
co.commit()
print()
print("(iii)")
print()
for i in data:
print(i)
# (iv) Display the Employee Number and Name who has the LIC insurance
print()
print("(iv)")
print()
for i in data:
print(i)
# (v) Update the salary by 10% for those employees whose designation is
Clerk.
print()
print("(v)")
print()
for i in data:
print("Updated Record: ", i)
'''
'''
10. Write a Python program using functions to create a text file
“Replace.txt”, read lines from the text file “Replace.txt” and remove all
the lines that contain the character 'a' in the file and write it to
another file called “New.txt”.
'''
'''
def WriteTxt():
fout = open("Replace.txt", "w")
rep = 'y'
while rep == 'y':
line = input("Enter the line to store: ")
fout.write(line)
fout.write('\n')
rep = input("Continues? (y/n): ")
fout.close()
def ReadTxt():
fin = open("Replace.txt")
fout = open("New.txt", "w")
for line in fin:
for i in line:
if i == 'a' or i == 'A':
print("Writing the line: ", line)
fout.write(line)
break
fin.close()
fout.close()
print("Reading from New.txt: ")
fin = open("New.txt")
for line in fin:
print(line.rstrip('\n'))
'''
11. Write a Python program using functions to create a text file
“Story.txt”, read lines from the text file “Story.txt” and display those
words whose length is less than 4 characters.
'''
'''
def WriteLines():
fout = open("Story.txt", "w")
rep = 'y'
while rep == 'y':
line = input("Enter the line to store: ")
print(line)
fout.write(line)
fout.write("\n")
rep = input("Continue? (y/n): ")
fout.close()
def ReadLines():
fin = open("Story.txt")
temp = fin.readlines()
t = []
for i in temp:
ts = i.split()
t.extend(ts)
print("Words lesser than 4 characters: ")
for i in range(len(t)):
if len(t[i]) < 4:
print(t[i])
fin.close()
WriteLines()
ReadLines()
'''
'''
12. Write a Python program using function to count the number of
words starting with the vowel in a file Books.txt
'''
'''
def WriteLines():
fout = open("Books.txt", "w")
rep = 'y'
while rep == 'y':
line = input("Enter the line to store: ")
fout.write(line)
fout.write("\n")
rep = input("Continue? (y/n): ")
fout.close()
def ReadLines():
vowels = ['a', 'e', 'i', 'o', 'u']
fin = open("Books.txt")
temp = fin.readlines()
ct = 0
t = []
for i in temp:
ts = i.split()
t.extend(ts)
for i in range(len(t)):
if t[i][0] in vowels:
ct = ct + 1
print("Number of words starting with a vowel:", ct)
fin.close()
WriteLines()
ReadLines()
'''
'''
13. Write a Python program which has the function to read from the
file Exam.txt and display all the lines which ends with the word
“health”.
'''
'''
def WriteLines():
fout = open("Exam.txt", "w")
rep = 'y'
while rep == 'y':
line = input("Enter the line to store: ")
fout.write(line)
fout.write("\n")
rep = input("Continue? (y/n): ")
fout.close()
def ReadLines():
fin = open("Exam.txt")
temp = fin.readlines()
t = []
for i in temp:
ts = i.rstrip("\n")
t.append(ts)
print("Lines that end with 'health': ")
for i in t:
if i[-6:] == 'health':
print(i)
fin.close()
WriteLines()
ReadLines()
'''
'''
14. Write an interactive menu driven Python program using binary
file to perform the following tasks:
(i) Write the information of the car like CarNo, Carname,
mileage and price onto the file “CARS.DAT”
(ii) Read from the file and display all the “Toyota cars” with
their price.
'''
'''
import pickle
def WriteCar():
fout = open("Cars.dat", "wb")
rep = 'y'
while rep == 'y':
l = []
carno = int(input("Enter Car No: "))
l.append(carno)
carname = input("Enter Car Name: ")
l.append(carname)
mileage = float(input("Enter Mileage: "))
l.append(mileage)
price = float(input("Enter Car Price: "))
l.append(price)
pickle.dump(l, fout)
rep = input("Continue? (y/n): ")
fout.close()
def ReadCar():
l = []
fin = open("Cars.dat", "rb")
try:
while True:
l = pickle.load(fin)
for i in range(len(l)):
if l[i] == 'Toyota':
print(l, end=',')
except EOFError:
fin.close()
WriteCar()
ReadCar()
'''
'''
15. Write a Python program to update the binary file “Mobile.DAT”
containing the information about mobile like ModelNo, memorycard,
details and megapixel. The Modelno whose megapixel to be updated
are accepted from the user.
'''
'''
import pickle
import os
def WriteMobile():
fout = open("Mobile.dat", "wb")
rep = 'y'
while rep == 'y':
l = []
modelno = int(input("Enter Model No: "))
l.append(modelno)
memorycard = int(input("Size of Memory Card: "))
l.append(memorycard)
details = input("Details about the Mobile: ")
l.append(details)
megapixel = int(input("Megapixel: "))
l.append(megapixel)
pickle.dump(l, fout)
rep = input("Continue? (y/n): ")
fout.close()
def UpdateMobile():
fin = open("Mobile.dat", "rb")
fout = open("Temp.dat", "wb")
l = []
try:
while True:
l = pickle.load(fin)
for i in range(len(l)):
if l[0] == mn:
l[3] = mp
pickle.dump(l, fout)
except EOFError:
fin.close()
fout.close()
os.remove("Mobile.dat")
os.rename("Temp.dat", "Mobile.dat")
def ReadMobile():
fin = open("Mobile.dat", "rb")
l = []
try:
while True:
l = pickle.load(fin)
print(l)
except EOFError:
fin.close()
WriteMobile()
mn = int(input("Enter the Model No. to be updated: "))
mp = int(input("Enter the Megapixel to be updated: "))
UpdateMobile()
ReadMobile()
'''
'''
16. Write a Python program to do the following :
(i) Write the information of the directory details like name,
address, areacode and phone number on to the binary file
“Telephone.DAT”
(ii) Delete all the records where the areacode is “TP101”.
(iii) Read from the file and display the details of all the records
and also to count the number of records present in it.
'''
'''
import pickle
import os
def WriteTP():
fout = open('Telephone.dat', 'wb')
rep = 'y'
while rep == 'y':
dic = {}
dic['Name'] = input("Enter Name: ")
dic['Address'] = input("Enter Address: ")
dic['Areacode'] = input("Enter Area Code: ")
dic['PhoneNo'] = int(input("Enter Phone Number: "))
pickle.dump(dic, fout)
rep = input('Continue? (y/n): ')
fout.close()
def UpdateTP():
fin = open('Telephone.dat', 'rb')
fout = open('Temp.dat', 'wb')
try:
while True:
dic = pickle.load(fin)
if dic['Areacode'] != 'TP101':
pickle.dump(dic, fout)
except EOFError:
fin.close()
fout.close()
os.remove('Telephone.dat')
os.rename('Temp.dat', 'Telephone.dat')
def ReadTP():
fin = open('Telephone.dat', 'rb')
ct = 0
try:
while True:
dic = pickle.load(fin)
ct = ct + 1
print(dic)
except EOFError:
fin.close()
print("Number of rows: ", ct)
WriteTP()
UpdateTP()
ReadTP()
'''
'''
17. Write an interactive Python program using functions to perform
the writing operation onto the csv file “Student.csv”. The details to be
written are Rno, Name, Marks in 5 subjects and Average. Read from
the “Student.csv” file and display the details of those students whose
Average is above 85.
'''
'''
import csv
def WriteCSV():
with open("Student.csv", 'w', newline='') as fout:
csvw = csv.writer(fout, delimiter=',')
rep = 'y'
while rep == 'y':
rno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
sub1 = float(input("Enter Physics Mark: "))
sub2 = float(input("Enter Chemistry Mark: "))
sub3 = float(input("Enter Computer Science Mark: "))
sub4 = float(input("Enter Math Mark: "))
sub5 = float(input("Enter English Mark: "))
avg = (sub1 + sub2 + sub3 + sub4 + sub5) / 5
l = [rno, name, sub1, sub2, sub3, sub4, sub5, avg]
csvw.writerow(l)
rep = input("Continue? (y/n): ")
def ReadCSV():
with open("Student.csv") as fin:
csvr = csv.reader(fin)
print("Students with Average greater than 85: ")
for row in csvr:
if float(row[7]) > 85:
print(row)
WriteCSV()
ReadCSV()
'''
'''
18. Write a Python program using functions to write the details of
Employee on to the file “Emp.csv” which has the following: Eno,
Name, Designation, Department and Salary. Read from the file and
display the Name and Salary of the Managers who belong to Sales
department.
'''
'''
import csv
def WriteCSV():
with open("Emp.csv", 'w', newline='') as fout:
csvw = csv.writer(fout, delimiter=',')
rep = 'y'
while rep == 'y':
eno = int(input("Enter Employee's No: "))
name = input("Enter Employee's Name: ")
desig = input("Enter Employee's Designation: ")
dept = input("Enter Employee's Department: ")
salary = float(input("Enter Employee's Salary: "))
l = [eno, name, desig, dept, salary]
csvw.writerow(l)
rep = input("Continue? (y/n): ")
def ReadCSV():
with open('Emp.csv') as fin:
csvr = csv.reader(fin)
for row in csvr:
if row[3] == 'Sales' and row[2] == 'Manager':
print()
print("Employee's Name:", row[1])
print("Employee's Salary:", row[4])
WriteCSV()
ReadCSV()
'''
'''
19. Write an interactive Python program using the functions
DoPush(Customer), DoPop(Customer) and DoShow(Customer) to
push,pop and display the Customer details like Customer ID, Name,
Phone no from the Stack of Customers.
'''
'''
def IsEmpty(Customer):
if not Customer:
return True
else:
return False
def DoPop(Customer):
if IsEmpty(Customer):
print('Underflow')
else:
Item = Customer.pop()
if len(Customer) == 0:
top = None
else:
top = len(Customer) - 1
return Item
def DoShow(Customer):
if IsEmpty(Customer):
print('Stack is empty')
else:
top = len(Customer) - 1
for i in range(top, -1, -1):
print("Customer ID: ", Customer[i][0])
print("Customer Name: ", Customer[i][1])
print("Customer's Phone No: ", Customer[i][2])
Customer = []
top = None
while True:
print('1. Push')
print('2. Pop')
print('3. Display')
print('4. Exit')
choice = int(input('Enter your choice: '))
if choice == 1:
Item = eval(input('Enter Customer Details: '))
DoPush(Customer, Item)
elif choice == 2:
Item = DoPop(Customer)
if Item == 'Underflow':
print('Stack is empty')
else:
print('Popped Item:', Item)
elif choice == 3:
DoShow(Customer)
elif choice == 4:
break
else:
print('Invalid choice.')
'''
'''
20. BCCI has created a dictionary containing top players and their runs as
key value pairs of cricket team. Write a program, with separate user
defined functions to perform the following operations:
1. Push the keys (name of the players) of the dictionary into a stack,
where the corresponding value (runs) is greater than 49.
2. Pop and display the content of the stack.
'''
'''
def IsEmpty(stack):
if not stack:
return True
else:
return False
def Pop(stack):
if IsEmpty(stack):
print('Underflow')
else:
item = stack.pop()
if len(stack) == 0:
top = None
else:
top = len(stack) - 1
return item
def Display(stack):
if IsEmpty(stack):
print('Stack is empty')
else:
top = len(stack) - 1
for i in range(top, -1, -1):
print(stack[i])
stack = []
top = None
while True:
print('1. Push')
print('2. Pop')
print('3. Display')
print('4. Exit')
choice = int(input('Enter your choice: '))
if choice == 1:
item = eval(input('Enter Player Details: '))
for i in item:
if item[i] > 49:
Push(stack, i)
elif choice == 2:
item = Pop(stack)
if item == 'Underflow':
print('Stack is empty')
else:
print('Popped Item:', item)
elif choice == 3:
Display(stack)
elif choice == 4:
break
else:
print('Invalid choice.')
'''