0% found this document useful (0 votes)
9 views45 pages

Computer Science Practical Programs

Uploaded by

niharikars.bsc23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views45 pages

Computer Science Practical Programs

Uploaded by

niharikars.bsc23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

# 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): ")
'''

'''2. Write an interactive Python program to do the following using


functions :
(i) Accept a list of elements and exchange the first half with the
second half of the list.
(ii) Accept a list of strings and display the number of palindrome
words present in it.'''

'''
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.")
'''

'''3. Write an interactive Python program using functions to find the


sum of boundary, non-boundary, left diagonal and right diagonal
elements of a nested List A of size MxN'''

'''
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

def NonBoundary(l, m, n):


sum = 0
for i in range(m):
for j in range(n):
if not (i == 0 or i == m - 1 or j == 0 or j == n - 1):
sum += l[i][j]
return sum

def LeftDiagonal(l, m, n):


sum = 0
if m != n:
return
else:
for i in range(m):
for j in range(n):
if i == j:
sum += l[i][j]
return sum

def RightDiagonal(l, m, n):


sum = 0
if m != n:
return
else:
for i in range(m):
for j in range(n):
if i + j == m - 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)

print("Sum of Boundary Elements: ", Boundary(l, m, n))


print("Sum of Non-Boundary Elements: ", NonBoundary(l, m, n))
print("Sum of Left Diagonal Elements: ", LeftDiagonal(l, m, n))
print("Sum of Right Diagonal Elements: ", RightDiagonal(l, m, n))
'''

'''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()

# Creating the tables

cu.execute("create table Worker(Ecode int, Name varchar(20), Desig


varchar(20), Plevel varchar(20), Doj date, dob date)")
cu.execute("create table Paylevel(Plevel varchar(20), Pay int, Allowance
int)")

print("1. Tables created.")

# 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')")

cu.execute("insert into Paylevel values('P001', 26000, 12000)")


cu.execute("insert into Paylevel values('P002', 22000, 10000)")
cu.execute("insert into Paylevel values('P003', 12000, 6000)")

print("2. Records Inserted.")

co.commit()

# (i) To display the details of all the WORKERS in descending order of their
DOJ.

cu.execute("SELECT * FROM WORKER ORDER BY DOJ DESC")


data = cu.fetchall()

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.

cu.execute("SELECT NAME, DESIG FROM WORKER WHERE PLEVEL IN


('P001','P002')")
data = cu.fetchall()

print()
print("(ii)")
print()

for i in data:
print(i)

# (iii) To display the number of workers whose PAY+ALLOWANCE is more


than 30000 for every PLEVEL.

cu.execute("SELECT COUNT(*) FROM WORKER, PAYLEVEL WHERE


WORKER.PLEVEL = PAYLEVEL.PLEVEL AND PAY+ALLOWANCE >30000
GROUP BY WORKER.PLEVEL")
data = cu.fetchall()

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)

# (v) To display the number of Workers designation wise.

cu.execute("SELECT COUNT(*),DESIG FROM WORKER GROUP BY DESIG")


data = cu.fetchall()

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

co = spc.connect(host='localhost', user='toor', passwd='',


database='JothishKamal')
cu = co.cursor()

# Creating Tables

cu.execute("create table Sports(Scode int, Sportsname varchar(20),


Participants int, Prizemoney int, Scheduledate date)")
cu.execute("create table Coach(Code int, Name varchar(20), Scode int)")

print("1. Tables created.")

# Inserting Records

cu.execute("insert into Sports values(101, 'Carrom', 2, 5000, '2012-01-


23')")
cu.execute("insert into Sports values(102, 'Badminton', 2, 12000, '2011-
12-12')")
cu.execute("insert into Sports values(103, 'Table Tennis', 4, 8000, '2012-
02-14')")
cu.execute("insert into Sports values(105, 'Chess', 2, 9000, '2012-01-
01')")
cu.execute("insert into Sports values(108, 'Lawn Tennis', 4, 25000, '2012-
03-19')")

cu.execute("insert into Coach values(1, 'Ravi', 101)")


cu.execute("insert into Coach values(2, 'Mohan', 108)")
cu.execute("insert into Coach values(3, 'Sameer', 101)")
cu.execute("insert into Coach values(4, 'Shikhar', 103)")

print("2. Records Inserted.")

co.commit()

# (i) To display scode, the number of coaches for each scode from the
table coach and display scode in descending order.

cu.execute("SELECT SCODE, COUNT(*) FROM COACH GROUP BY SCODE


ORDER BY SCODE DESC")
data = cu.fetchall()

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.

cu.execute("SELECT * FROM SPORTS NATURAL JOIN COACH WHERE


SCHEDULEDATE LIKE '2019%';")
data = cu.fetchall()

print()
print("(iii)")
print()

for i in data:
print("EMPTY TABLE")

# (iv) To display number of different participants from the table sports.

cu.execute("SELECT DISTINCT PARTICIPANTS FROM SPORTS")


data = cu.fetchall()
print()
print("(iv)")
print()

for i in data:
print(i)

# (v) Increase the Participants by 6 for the sports carrom, chess and
badminton.

print()
print("(v)")
print()

cu.execute("UPDATE SPORTS SET PARTICIPANTS=PARTICIPANTS=6


WHERE SPORTSNAME IN ('CARROM','CHESS', 'BADMINTON')")
co.commit()

cu.execute("SELECT * FROM SPORTS")


data = cu.fetchall()

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

co = spc.connect(host='localhost', user='toor', passwd='',


database='JothishKamal')
cu = co.cursor()

# Creating Tables

cu.execute("create table Teacher(T_id int, Name varchar(20), Age int,


Department varchar(20), Date_of_join date, Salary bigint, Gender
char(1))")
cu.execute("create table Posting(P_id int, Department varchar(20), Place
varchar(20))")

print("1. Tables created.")

# Inserting records

num = int(input("Enter the number of records(Teacher) you want to enter:


"))
num2 = int(input("Enter the number of records(Posting) you want to
enter: "))
for i in range(num):
tid = int(input("Enter Teacher's ID: "))
name = input("Enter Teacher's Name: ")
age = int(input("Enter Teacher's Age: "))
dep = input("Enter Teacher's Department: ")
doj = input("Enter Teacher's DOJ: ")
sal = int(input("Enter Teacher's Salary: "))
gen = input("Enter Teacher's Gender: ")
query = "insert into Teacher values(%s, '%s', %s, '%s', '%s', %s, '%s')"
% (tid, name, age, dep, doj, sal, gen)
cu.execute(query)
co.commit()

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("2. Records Inserted")

# (i) To display the total number of teachers Department wise.

print()
print("(i)")
print()

cu.execute("SELECT DEPARTMENT, COUNT(*) FROM TEACHER GROUP BY


DEPARTMENT")
data = cu.fetchall()

for i in data:
print(i)

# (ii) To display the Teacher details who have been posted in “Delhi”.

print()
print("(ii)")
print()

cu.execute("SELECT * FROM TEACHER NATURAL JOIN POSTING WHERE


PLACE = 'DELHI'")
data = cu.fetchall()

for i in data:
print(i)

# (iii) To display the highest salary being paid in each department.

print()
print("(iii)")
print()

cu.execute("SELECT DEPARTMENT, MAX(SALARY) FROM TEACHER GROUP


BY DEPARTMENT")
data = cu.fetchall()

for i in data:
print(i)

# (iv) To display the total salary being paid for male and female
separately.
print()
print("(iv)")
print()

cu.execute("SELECT GENDER, SUM(SALARY) FROM TEACHER GROUP BY


GENDER")
data = cu.fetchall()

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()

cu.execute("UPDATE TEACHER SET SALARY = SALARY + SALARY * 0.1


WHERE DATE_OF_JOIN LIKE '2017%' OR DATE_OF_JOIN LIKE '2018%';")
co.commit()

cu.execute("SELECT * FROM TEACHER WHERE DATE_OF_JOIN LIKE '2017%'


OR DATE_OF_JOIN LIKE '2018%'")
data = cu.fetchall()

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.

cu.execute("create table Student(admno int, sname varchar(20), gender


char(1), dob date, stream varchar(20), average float check(average >= 0
and average <= 100))")

print("(i) Table created.")

# (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()

print("(ii) Records Inserted.")

# (iii) Increase the marks by 5 for those students who belong to science
stream.

cu.execute("UPDATE STUDENT SET AVERAGE = AVERAGE + 5 WHERE


STREAM = 'SCIENCE'")

cu.execute("SELECT * FROM STUDENT WHERE STREAM = 'SCIENCE'")


data = cu.fetchall()

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()

cu.execute("SELECT COUNT(*) FROM STUDENT WHERE GENDER = 'M' AND


STREAM = 'COMMERCE'")
data = cu.fetchall()

for i in data:
print(i)

# (v) Delete the records of those students whose average<40

cu.execute('SELECT * FROM STUDENT WHERE AVERAGE < 40')


data = cu.fetchall()

cu.execute("DELETE FROM STUDENT WHERE AVERAGE < 40")

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()

# (i) Create 2 tables


# ● Table name - Event with EventId, Eventname, NumPerformers,
# CelebrityID.
# ● Table name – Celebrity with CelebrityID, Name, Phone,
# FeeCharged

cu.execute("create table Event(EventID int, EventName varchar(20),


NumPerformers int, CelebrityID varchar(20))")
cu.execute("create table Celebrity(CelebrityID varchar(20), Name
varchar(20), Phone bigint, FeeCharged bigint)")

print("(i) Tables created.")

# (ii) Insert 5 records in both the tables


cu.execute("insert into Event values(101, 'Birthday', 10, 'C102')")
cu.execute("insert into Event values(102, 'Promotion Party', 20, 'C103')")
cu.execute("insert into Event values(103, 'Engagement', 12, 'C102')")
cu.execute("insert into Event values(104, 'Wedding', 15, 'C104')")
cu.execute("insert into Event values(105, 'Birthday', 17, 'C101')")

cu.execute("insert into Celebrity values('C101', 'Faiz Khan', 9910195610,


200000)")
cu.execute("insert into Celebrity values('C102', 'Sanjay Kumar',
8934664481, 250000)")
cu.execute("insert into Celebrity values('C103', 'NeeraKhan Kapoor',
9811665685, 300000)")
cu.execute("insert into Celebrity values('C104', 'Reena Bhatia',
6587775645, 100000)")

co.commit()

print("(ii) Records inserted.")

# (iii) Display the Eventname, Name of celebrity and Feecharged for those
celebrities who charge more than 200000

cu.execute("select Eventname, Name, Feecharged from Event, Celebrity


where Event.CelebrityId = Celebrity.CelebrityId and Feecharged >
200000")
data = cu.fetchall()

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

cu.execute("update Event, Celebrity set Feecharged = Feecharged +


10000 where Event.CelebrityId = Celebrity.CelebrityId and
NumPerformers > 15")
co.commit()

cu.execute("SELECT * FROM CELEBRITY NATURAL JOIN EVENT WHERE


NUMPERFORMERS > 15")
data = cu.fetchall()

print()
print("(iv)")
print()

for i in data:
print(i)

# (v) Delete the records of those Celebrity whose name starts with R.

cu.execute("SELECT * FROM CELEBRITY WHERE NAME LIKE 'R%'")


data = cu.fetchall()

cu.execute("DELETE FROM CELEBRITY WHERE NAME LIKE 'R%'")


co.commit()

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()

# (i) Create 2 tables


# ● Table name - Employee with Empno, Name, Desig, Salary, Leave,
Bonus.
# ● Table name – Insurance with Empno, LIC

cu.execute("create table Employee(EmpNo int, Name varchar(20), Desig


varchar(20), Salary bigint, Leaves int, Bonus int)")
cu.execute("create table Insurance(EmpNo int, LIC varchar(20))")

print("(i) Tables created.")

# (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("(ii) Inserted Records.")

# (iii) Display the total salary of each designation of those employees


whose name starts with ‘R’.
cu.execute("SELECT SUM(SALARY), DESIG FROM EMPLOYEE WHERE NAME
LIKE 'R%' GROUP BY DESIG")
data = cu.fetchall()

print()
print("(iii)")
print()

for i in data:
print(i)

# (iv) Display the Employee Number and Name who has the LIC insurance

cu.execute("SELECT EMPLOYEE.EMPNO, NAME FROM EMPLOYEE NATURAL


JOIN INSURANCE WHERE LIC = 'YES'")
data = cu.fetchall()

print()
print("(iv)")
print()

for i in data:
print(i)

# (v) Update the salary by 10% for those employees whose designation is
Clerk.

cu.execute("UPDATE EMPLOYEE SET SALARY = SALARY + 0.1*SALARY


WHERE DESIG = 'CLERK'")
co.commit()
cu.execute("SELECT * FROM EMPLOYEE WHERE DESIG = 'CLERK'")
data = cu.fetchall()

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'))

print("Creating Text File(Replace.txt).")


WriteTxt()
print("Reading Text File(New.txt).")
ReadTxt()
'''

'''
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 DoPush(Customer, Item):


Customer.append(Item)
top = len(Customer) - 1

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 Push(stack, item):


stack.append(item)
top = len(stack) - 1

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.')
'''

You might also like