You are on page 1of 49

# Program 1

# Write an interactive menu driven program to apply linear and binary search for a list of
# strings using functions.
Code:
def binary():
r='false'
a.sort()
if val <= (len(a)//2):
for i in range(0, ((len(a)//2)+1)):
if str(a[i]) == str(val):
r='true'
elif val >= (len(a)//2):
for j in range(((len(a)//2)-1),len(a)):
if str(a[j]) == str(val):
r='true'
if r == 'true':
print(val,' is found in the list')
elif r=='false':
print(val,' is not found in the list')

def linear():
r1='false'
for i in a:
if str(i) == str(val) :
r1='true'
if r1=='true':
print(val,' is found in the list')
elif r1=='false':
print(val,' is not found in the list')

l=input("Enter the list values:")


val=int(input("Enter the value to search:"))
a=l.split(',')
choise=input("Which type of search you want to use \n(a) Binary or (b) Linear:")
if choise == 'a':
binary()
elif choise =='b':
linear()
Output:
#Program 2
# a Python program using function to sort the details of
# Doctors in descending order of their specialization using bubble
# sort. The Doctors detail includes DoctorId, Name and specialization
# which is stored as a nested list.

Code:
def bsort(a, b=2):
n = len(a)
for i in range(n - 1):
for j in range(n - i - 1):
if a[j][b] < a[j + 1][b]:
a[j], a[j + 1] = a[j + 1], a[j]
print(a)

while 1:
print(" SORTING")
print(" ~~~~~~~")
print(" 1. Create a List")
print(" 2. Sort the List")
print(" 3. Exit")
ch = int(input(" Enter your choice : "))
if ch == 1:
m = int(input("Enter the number of elements: "))
a = [input(f"Enter Doctor's Id, Doctor's Name and Specialization of the Doctor's
code {i+1} separated by comma: ").split(",") for i in range(m)]
for i in a:
i[0] = int(i[0])
elif ch == 2:
bsort(a)
elif ch == 3:
print("Exiting the program...")
break
else:
print("Wrong Choice")
Output:
#Program 3
# A Python program which has the function to sort the
# details of the Products in ascending order of their price using
# insertion sort. The nested list contains the details of the Product
# such as Pid, Pname, Qty and price.
Code:
def isort(a, b=3):
for i in range(1, len(a)):
k = a[i][b]
j=i-1
while j >= 0 and k < a[j][b]:
a[j + 1], a[j] = a[j], a[j + 1]
j -= 1
a[j + 1][b] = k
print(a)
while 1:
print(" SORTING")
print(" ~~~~~~~")
print(" 1. Create a List")
print(" 2. Sort the List")
print(" 3. Exit")
ch = int(input(" Enter your choice : "))
if ch == 1:
n = int(input(" Enter the number of elements: "))
print(" Enter in the order ProductID, ProductName, Qty, Price ")
a = [input(f" for element {i+1} separated by comma: ").split(", ") for i in range(n)]
for i in a:
i[0], i[2], i[3] = int(i[0]), int(i[2]), int(i[3])
elif ch == 2:
isort(a)
elif ch == 3:
print(" Exiting the program... ")
break
else:
print(" Wrong choice")
Output:
# Program 4

# A Python program using functions to create a text file Story.txt

# Read files from the text file Story.txt and display those words

# whose length is less than 4 characters

Code:
def create(file):

with open(file,"w") as f:

chr = input(f"Enter the details in the file {f}: ")

f.write(chr)

print("File created successfully")

def display(file):

print("Words with length lass than 4 are ")

with open(file, "r") as f:

line = f.read()

for i in line.split():

if(len(i) < 4):

print(i)

while True:

print(""" Creating a file

~~~~~~~~~~~~~~~""")
print("""

1) Create a File

2) Display the words

3) Close""")

ch = int(input(" Enter your choice : "))

if ch == 1:

file = input("Enter the file name: ")

create(file)

elif ch == 2:

file = input("Enter the file name: ")

display(file)

elif ch == 3:

print("Closing...")

break

else:

print("Enter the correct option.")


Output:
# Program 5
# A Python program using function to count the number
# of words starting with the vowel in a file Books.txt
Code:

def create(file):
with open(file,"w") as f:
chr = input(f"Enter the details in the file {f}: ")
f.writelines(chr)
print("File created successfully")

def func(file):
with open(file, "r") as f:
count = 0
for line in f:
for word in line.split():
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
count += 1
print("No.of words that start with vowel are", count)

while True:
print(""" Counting Vowels in a file
~~~~~~~~~~~~~~~~~~~~~~~~~""")
print("""
1) Create a File
2) Display the number of words starting with a Vowel
3) Close""")
ch = int(input(" Enter your choice : "))
if ch == 1:
file = input("Enter the file name: ")
create(file)
elif ch == 2:
File = input("Enter the filename: ")
func(File)
elif ch == 3:
print("Closing...")
break
else:
print("Enter the correct option.")
Output:
# Program 6
# 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”

Code:
def lasth(filename):
with open(filename,"r") as f:
a=f.readlines()
for i in a:
if "health." in i:
print(i)
def wte(chr):
with open("Exam.txt","w") as g:
g.write(chr)

while True:
print(" LINE ENDING WITH HEALTH ")
print(" ~~~~~~~~~~~~~~~~~~~~~~~")
print("""
1)Write into file
2)View line ending with health
3)close the file
""")
chh = input("Enter your choice : ")

if chh=='1':
chr=input("Enter the details in the file")
wte(chr)
elif chh=='2':
lasth("Exam.txt")
elif chh=='3':
print("closing...")
break
else:
print("wrong input")
Output:
# Program 7
# 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
“CARS.DAT” (ii) Read from the file and display all the Toyota cars with their price.
Code:
import pickle
def insert():
a=int(input("enter number of cars"))
with open('CARS.dat', 'ab+') as f:
for i in range(1,a+1):
a=input(f"enter car number of car {i}: ")
b=input(f"car name of car {i}: " )
c=input(f"enter car milage of car {i}: ")
d=input(f"enter car price of car {i}: ")
x=f"carno = {a},carname = {b},milage = {c},price={d}\n"
pickle.dump(x,f)
def dis():
m= open("CARS.dat","rb")
while True:
try:
x= pickle.load(m)
print(x)
except EOFError:
break
m.close
while True:
print(" BINARY FILE ")
print(" ~~~~~~~~~~~")
print("""
1)write information of the car
2)View the detailss of the file
3)close
""")
mu=input("Enter your choice")
mu = mu.lower()
if mu=='1':
insert()
elif mu=='2':
dis()
elif mu == "3":
print("closing")
break
else:
print("wrong input")
Output:
# Program 8

# 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.

Code:
import pickle
def show():
with open('mobile.dat','rb') as f:
dp=pickle.load(f)
print('Mobile records',dp)
global d
d=[]
d.append(dp)

def update():
with open('mobile.dat','wb') as k:
ans='false'
number=str(input('Enter the model number to update:'))
for i in range(len(d[0])):
if str(d[0][i][0]) == str(number):
mp=str(input('Enter the new megapixel:'))
d[0][i][2]=mp
ans='true'
print('Record updated')
if ans == 'false':
print('No such model number')
pickle.dump(d,k)

while 1>0:
choise=str(input('What do you want to do:\n(a)View records\n(b)Update
record\n>>>'))
if choise == 'a':
show()
elif choise == 'b':
update()
Output:
# Program 9
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

Code:
import pickle
def write():
d=[]
with open('telephone.dat','wb') as f:
name=input('Enter the name:')
address=input('Enter the address:')
areacode=input('Enter the areacode:')
ph_no=int(input('Enter the phone number'))
d.append([name,address,areacode,ph_no])
pickle.dump(d,f)
def delete():
d=[]
with open('telephone.dat','rb') as k:
d=pickle.load(k)
with open('telephone.dat','wb') as h:
found=False
val ='TP101'
d1=[]
for i in range(len(d)):
if d[i][2] != val:
d1.append(d[i])
pickle.dump(d1,h)
def read():
d=[]
with open('telephone.dat','rb') as k:
ans='y'
while True:
try:
d=pickle.load(k)
except EOFError:
break
for i in d:
print(i)
l=len(d)
print('The number of records:',l)
while 1>0:
choise=str(input('What do you want to do\n(a)Write\n(b)Delete\n(c)View\n>>> '))
if choise == 'a':
write()
elif choise == 'b':
delete()
elif choise == 'c':
read()
Output:
# Program 10
Write an interactive Python program to perform the writing operation on to 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.

Code:
import csv
r=True
def func():
with open("students.csv",'w',newline='') as f:
a=csv.writer(f)
a.writerow(val)
with open("students.csv") as f:
d=csv.reader(f)
for j in d:
if int(j[3]) > 85:
v.append(j)
v=[]
while r is True:
rno=int(input("Enter the Rool number:"))
name=str(input("Enter the student name:"))
marks=input("Enter the marks:")
avg=input("Average:")
val=[rno,name,marks,avg]
func()
choise=input("Do you want to continue(y/n): ")
if choise == 'y':
continue
else:
print('Students has 85 average are: ', v)
break
Output:
# Program 11 # 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.
Code:
import csv
def write_func(file):
print("The file contains header Eno,Name,Designation,Department,Salary")
n = int(input("Enter no.of records to be added: "))
li = [input(f"Enter the record {i+1} separated by comma: ").split(",") for i in range(n)]
for i in range(len(li)):
li[i][0], li[i][4] = int(li[i][0]), int(li[i][-1])
with open(file,"w",newline='') as f:
writer = csv.writer(f)
writer.writerow(["Eno","Name","Designation","Department","Salary"])
writer.writerows(li)
def read_func(file):
desig = input("Enter the designation: ")
dept = input("Enter the department: ")
l = []
with open(file,"r") as f:
reader = csv.reader(f)
next(reader)
for line in reader:
if line[2].lower() == desig.lower() and line[3].lower() == dept.lower():
l += line[1::3]
if l == []: l = None
print(f"Name and salary of {dept} {desig}(s) are",l)
print(" Heading")
print(" ~~~~~~~")
file = input("Enter the file name: ")
while True:
ch = int(input("""Menu:
1) Write
2) Read and display
3) Exit
Choose and option: """))
if ch == 1:
write_func(file)
elif ch == 2:
read_func(file)
elif ch == 3:
print("Exiting the program...")
break else:
print("Invalid entry! Try again.")
Output:
# Program 12
# An interactive Python program to find the sum of
# boundary, non-boundary, left diagonal and right diagonal elements
# of a nested List A of size MxN.
Code:
def bord_ele(l):
bsum = 0
for i in range(len(l)):
for j in range(len(l)):
if i == 0 or j == 0 or i == len(l) - 1 or j == len(l) - 1:
bsum += l[i][j]
print("\nThe sum is ", bsum)
def non_bord(l):
nbsum = 0
for i in range(len(l)):
for j in range(len(l)):
if i != 0 and j != 0 and i != len(l) - 1 and j != len(l) - 1:
nbsum += l[i][j]
print("\nThe sum is ", nbsum)
def rdiag(l):
rdsum = 0
for i in range(len(l)):
c = len(l) - i - 1
rdsum += l[i][c]
print("\nThe sum is ", rdsum)
def ldiag(l):
ldsum = 0
for i in range(len(l)):
for j in range(len(l)):
if i == j:
ldsum += l[i][j]
print("\nThe sum is ", ldsum)
print(" Matrix")
print(" ~~~~~~")
c = input("Enter the dimension of the matrix (M*N): ")
l = [input(f"Enter row {i+1} separated by comma: ").split(",") for i in range(int(c[0]))]
while True:
ch = int(input("""Menu:
1) Sum of boundary elements
2) Sum of Non-Boundary elements
3) Sum of Left diagonal elements
4) Sum of Right diagonal elements
5) Exit

Enter you choice: """))


for i in range(len(l)):
for j in range(len(l)):
l[i][j] = int(l[i][j])
if ch == 1:
bord_ele(l)
elif ch == 2:
non_bord(l)
elif ch == 3:
ldiag(l)
elif ch == 4:
rdiag(l)
elif ch == 5:
print("Exiting the program...")
break
else:
print("Invalid Entry! Try again.")
Output:
# Program 13
# 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

Code:
def swap_lis(l):
if len(l)%2 == 0:
l = l[len(l)//2:]+l[:len(l)//2]
print("The swapped list is",l)
else:
print("Enter a list with Even no. of elements and try again.")
def check_pal(s):
count = 0
for i in s:
if i == i[::-1]:
count += 1
print("No. of palindrome words in the list:", count)
print(" Heading")
print(" ~~~~~~~")
while 1:
ch = int(input("""Menu:
1) Swap the elements of a list
2) Check the no. of palindrome words
3) Exit

Choose an option: """))


if ch == 1:
l = input("Enter the elements separated by comma: ").split(",")
for i in range(len(l)):
if l[i].isdigit():
l[i] = int(l[i])
swap_lis(l)
elif ch == 2:
s = input("Enter the elements of the list separated by comma: ").split(",")
check_pal(s)
elif ch == 3:
print("Exiting the program...1")
break
else:
print("Invalid Entry! Try again.")
Output:
# Program 14
# 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.

Code:
def DoPush(Customer):
data = input("\nEnter the data separated by comma(, ): ").split(",")
data[0], data[2] = int(data[0]), int(data[2])
Customer.append(data)
print("Data added successfully.\n")
def DoPop(Customer):
print("The popped element is", Customer.pop())
def DoShow(Customer):
print("The stack is", Customer)

print(" Heading")
print(" ~~~~~~~")
n = int(input("Enter the no.of elements in the stack: "))
print("The stack should contain Customer ID, Name, Phone no")
l = [input(f"Enter element {i+1} separated by comma(, ): ").split(", ") for i in range(n)]
for i in range(len(l)):
l[i][0],l[i][2] = int(l[i][0]),int(l[i][2])

while True:
ch = int(input("""Menu:
1) Push
2) Pop
3) Show
4) Exit
Choose an option: """))
if ch == 1:
DoPush(l)
elif ch == 2:
DoPop(l)
elif ch == 3:
DoShow(l)
elif ch == 4:
print("Exiting the program...")
break
else:
print("Invalid Entry! Try again.")
Output:
# Program 15
# An interactive Python program using the functions
# InsQueue(Passenger), DelQueue(Passenger),
# DispQueue(Passenger) to add, delete and display the Passenger
# details like Passenger name and ticketno
Code:
def InsQueue(Passenger):
data = input("\nEnter the data separated by comma(, ): ").split(", ")
data[1] = int(data[1])
Passenger.append(data)
print("Data added successfully.\n")
def DelQueue(Passenger):
print("The deleted element is",Passenger.pop(0))
def DispQueue(Passenger):
print("The Queue is",Passenger)

print(" Heading")
print(" ~~~~~~~")
n = int(input("Enter the no.of elements in the queue: "))
print("The queue should contain Passenger Name, Ticket No.")
l = [input(f"Enter element {i+1} separated by comma(, ): ").split(", ") for i in range(n)]
for i in range(len(l)):
l[i][1] = int(l[i][1])
while True:
ch = int(input("""Menu:
1) Insert
2) Delete
3) Show
4) Exit
Choose an option: """))
if ch == 1:
InsQueue(l)
elif ch == 2:
DelQueue(l)
elif ch == 3:
DispQueue(l)
elif ch == 4:
print("Exiting the program...")
break
else:
print("Invalid Entry! Try again.")
Output:
# Program 18

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.

Code:
import mysql.connector as sq

mycon= sq.connect(host="localhost",user="root",passwd="mvm",database="lokesh")

if mycon.is_connected():
print("Successfully connected to mysql database")

cur= mycon.cursor()

cur.execute("create table student(admno integer,sname varchar(50), gender varchar(2), dob date,


stream varchar(10), average integer);")

#Q1
'''

admno=int(input("Enter admno.:"))

sname=input("Enter sname:")
gender=input("Gender(M or F):")

dob=input("DOB(YYYY/MM/DD):")

stream=input("Stream:")
average=int(input("Average:"))

sql="insert into student (admno,sname,gender,dob,stream,average) values (%s, %s, %s, %s, %s,
%s)"
val=(admno,sname,gender,dob,stream,average)

cur.execute(sql,val)

mycon.commit()
print("Details inserted")

mycon.close()

'''
#Q2
'''

cur.execute("update student set average=average+5 where stream='science';")

mycon.commit()
print("Updated!")

mycon.close()

'''
#Q3

'''
cur.execute("select count(sname) from student where gender='M' and stream='Commerce';")
data=cur.fetchall()

for row in data:

print(row)
mycon.commit()

mycon.close()

'''

#Q4

'''
cur.execute("delete from student where average<40;")
mycon.commit()

mycon.close()
'''
Output:
# Program 19
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.

Code:
import mysql.connector as sq

mycon= sq.connect(host="localhost",user="root",passwd="mvm",database="lokesh")
if mycon.is_connected():

print("Successfully connected to mysql database")

cur= mycon.cursor()
'''

cur.execute("create table event(eventid varchar(5), eventname varchar(50), numperformers


integer, celebrityid varchar(5))")
cur.execute("create table celebrity(celebrityid varchar(5),name varchar(50),phone
varchar(50),feecharged integer);")

'''
#Q1
'''

eventid=int(input("Enter event ID.:"))


eventname=input("Enter event name:")

celebrityid=input("Celebrity ID:")

numperformance=int(input("number of performance:"))

sql="insert into event (eventid,eventname,numperformance,celebrityid) values (%s, %s, %s, %s)"

val=(eventid,eventname,numperformance,celebrityid)
cur.execute(sql,val)
mycon.commit()

print("Details inserted")
mycon.close()

'''

#Q2
'''

celebrityid=input("Enter celebrity ID.:")

name=input("Enter name:")
phone=input("Phone number:")

feecharged=int(input("fee charged:"))
sql="insert into celebrity (celebrityid,name,phone,feecharged) values (%s, %s, %s, %s)"
val=(celebrityid,name,phone,feecharged)

cur.execute(sql,val)

mycon.commit()
print("Details inserted")

mycon.close()

'''
#Q3

'''

cur.execute("select e.eventname,c.name,c.feecharged from event e,celebrity c where


feecharged>200000;")

data=cur.fetchall()
for row in data:
print(row)

mycon.commit()

mycon.close()
'''

#Q4

'''
cur.execute("update event e,celebrity c set c.feecharged=c.feecharged+10000 where
e.numperformance>15;")

mycon.commit()

print("Updated!")
mycon.close()

'''

#Q5
'''

cur.execute("delete from celebrity where name like 'R%';")

mycon.commit()
mycon.close()

'''
Output:
# Program 20

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 mc

mycon = mc.connect(user='root',password='1210',host='localhost',database='lokesh')

cur=mycon.cursor()

#Q1

'''

cur.execute("create table employee(empno int,name varchar(50),desig varchar(50),salary int,leav


int,bonus int);")

cur.execute("create table insurance(empno int, lic int);")


'''

#Q2
#1st table
'''

for i in range(5):
empno=int(input("Enter employee number:"))

name=input("Enter employee name:")

desig=input("Enter designation:")
salary=int(input("Enter salary:"))

leav=int(input("leave:"))
bonus=int(input("Bonus:"))
sql="insert into employee(empno,name,desig,salary,leav,bonus) values(%s,%s,%s,%s,%s,%s)"
val=(empno,name,desig,salary,leav,bonus)

cur.execute(sql,val)

mycon.commit()
'''

'''

#2nd table
for j in range(5):

empno=int(input("Enter employee number:"))


lic=int(input("Enter amount:"))

s="insert into insurance(empno,lic) values(%s,%s)"

v=(empno,lic)
cur.execute(s,v)

mycon.commit()

'''
#Q3

'''

cur.execute("select sum(salary) from employee group by desig having name like 'r%';")
ans= cur.fetchall()
for x in ans:

print(x)
'''

#Q4

'''
cur.execute("select i.empno,name from employee e,insurance i where e.empid=i.empid and lic is
not null; ")

ans=cur.fetchall()
for x in ans:
print(x)

'''

#Q5

'''
cur.execute("update employees set bonus=bonus*0.1 where desig='clerk';")

mycon.commit()

print("Updated!")
'''
Output:

You might also like