Practicalfileclass 12
Practicalfileclass 12
PRACTICAL FILE
(SESSION 2021-22)
def main():
list=[105, 99, 10, 43,62,8]
n=len (list)
print("original list: ", list)
for i in range (n-1):
for j in range (n-i-1 ):
if list [j] > list [j+1]:
list [j], list [j+1] = list [j+1], list [5]
print("List after sorting is: ", list)
main()
OUTPUT:
QUES 3 : Write a program that depending upon the user’s choice
either adds or removes an element from a stack.
ANSWER 3 :
CODE:
SCL=dict()
i=1
flag=0
n=int (input ("enter the no of entries: "))
while i<=n:
sno=input("\nenter sno: ")
name=input("Enter the name of student: ")
tname=input("Enter the name of teacher: ")
clas=input ("Enter class: ")
b=(name, tname, clas)
SCL [sno]=b
i=i+1
l =SCL.keys ()
for i in l:
print("\nsno", i,":")
z=SCL[i]
print("name\t","tname\t", "clas\t")
for j in z:
print (j, end="\t")
OUTPUT:
5 : WAP to input names of ‘n’ customers and their details like items brought, cost
and phone no. etc., store them in a dictionary and display all the details in tabular
form.
ANSWER 5 :
CODE:
SCL=dict()
i=1
flag=0
n=int (input ("enter the no of entries: "))
while i<=n:
sno=input("\nenter sno: ")
name=input("Enter the name of customer: ")
item=input("Enter the name of item bought: ")
qty=input("Enter the quantity: ")
cost=input("Enter cost of item: ")
phone=input("Enter customer phone no. :")
b=(name, item, qty, cost, phone)
SCL [sno]=b
i=i+1
l= SCL.keys ()
for i in l:
print("\nsno", i,":")
z=SCL[i]
print("name\t", "item\t","Qty\t", "cost\t", "phone\t")
for j in z:
print (j, end="\t")
OUTPUT:
QUES 6 : Write a menu driven program to store information about employee in
an employee table(MySQL) using functions and mysql connectivity,
Functions are: 1. Add() 2.Remove() 3.display() 4.exit()
ANSWER 6 :
CODE:
import mysql.connector
con = mysql.connector.connect(
host="localhost", user="root", password="ha@274k2", database="emp")
def Add_Employ():
Id = input("Enter Employee Id : ")
if(check_employee(Id) == True):
print("Employee aready exists\nTry Again\n")
menu()
else:
Name = input("Enter Employee Name : ")
Post = input("Enter Employee Post : ")
Salary = input("Enter Employee Salary : ")
data = (Id, Name, Post, Salary)
sql = 'insert into empd values(%s,%s,%s,%s)'
c = con.cursor()
c.execute(sql, data)
con.commit()
print("Employee Added Successfully ")
menu()
def Promote_Employee():
Id = int(input("Enter Employ's Id"))
if(check_employee(Id) == False):
print("Employee does not exists\nTry Again\n")
menu()
else:
Amount = int(input("Enter increase in Salary"))
sql = 'select salary from empd where id=%s'
data = (Id,)
c = con.cursor()
c.execute(sql, data)
r = c.fetchone()
t = r[0]+Amount
sql = 'update empd set salary=%s where id=%s'
d = (t, Id)
c.execute(sql, d)
con.commit()
print("Employee Promoted")
menu()
def Remove_Employ():
Id = input("Enter Employee Id : ")
if(check_employee(Id) == False):
print("Employee does not exists\nTry Again\n")
menu()
else:
sql = 'delete from empd where id=%s'
data = (Id,)
c = con.cursor()
c.execute(sql, data)
con.commit()
print("Employee Removed")
menu()
def check_employee(employee_id):
sql = 'select * from empd where id=%s'
c = con.cursor(buffered=True)
data = (employee_id,)
c.execute(sql, data)
r = c.rowcount
if r == 1:
return True
else:
return False
def Display_Employees():
sql = 'select * from empd'
c = con.cursor()
c.execute(sql)
r = c.fetchall()
for i in r:
print("Employee Id : ", i[0])
print("Employee Name : ", i[1])
print("Employee Post : ", i[2])
print("Employee Salary : ", i[3])
print(" \
\
\
")
menu()
def menu():
print("Welcome to Employee Management Record")
print("Press ")
print("1 to Add Employee")
print("2 to Remove Employee ")
print("3 to Promote Employee")
print("4 to Display Employees")
print("5 to Exit")
ch = int(input("Enter your Choice "))
if ch == 1:
Add_Employ()
elif ch == 2:
Remove_Employ()
elif ch == 3:
Promote_Employee()
elif ch == 4:
Display_Employees()
elif ch == 5:
exit(0)
else:
print("Invalid Choice")
menu()
menu()
OUTPUT:
QUES 7: Write a program for removing lowercase. Function name: remove
lowercase() that accepts 2 file names and copies all lines that do not start with
lowercase letters from the first file to the second file.
ANSWER 7 :
CODE:
def capitalize_sentance():
l=1
fl = open("sample.txt" ,'r')
f2 = open("sample2.txt" ,'w')
#print("file name: ",f1.name)
#lines =f1.readlines ()
while l:
line = fl.readline()
if not line:
break
line=line.rstrip ()
linelength = len (line)
str=''
str = str +line[0].upper()
i=l
while i < linelength:
if line[i] ==".":
str = str + line[i]
i = i+l
if i >= linelength:
break
str = str + line[i].upper()
else:
str = str + line[i]
i = i+l
f2.write(str)
else:
print("file does not exist")
fl.close()
f2.close()
capitalize_sentance()
OUTPUT:
QUES 8 : Write a python program to calculate the time taken to take numbers in
range(1,5)
ANSWER 8 :
CODE:
import time
start= time.time()
r=0
for i in range(5):
for n in range(5):
r=r+(i*n)
print(r)
end=time.time()
print(end-start)
OUTPUT:
QUES 9 : : Write a python program to find and display the prime numbers
between 2 and N. Pass N as argument in method.
ANSWER 9:
CODE:
lower = int(input ("Enter lower range: "))
upper = int(input ("Enter upper range: "))
for num in range (lower, upper + 1):
if num > 1:
for i in range (2, num):
if (num & i) ==0:
break
else:
print (num)
OUTPUT:
QUES 10 : #write a menu driven program using function to insert product
name, show product list ,remove last product and exit from program
ANSWER 10 :
CODE:
p=[]
def main():
global p
print("a. Insert product name")
print("b. Show product list")
print("c. Exit from program")
print("d. Remove last element")
ch=input("Enter choice(a,b,c): ")
if ch=='a':
pro(p)
main()
elif ch=='b':
show1(p)
main()
elif ch=='c':
print("ended")
elif ch=='d':
rem(p)
main()
def pro(lis):
a = input("Enter Product name: ")
lis.append(a)
def show1(lis):
print("Your Product List: ",lis)
def rem(lis):
print("This item has been removed: ",lis.pop())
print("Modified list: ",lis)
def set_data():
empcode = int(input('Enter Employee code: '))
name = input('Enter Employee name: ')
salary = int(input('Enter salary: '))
print()
#create a list
employee = [empcode,name,salary]
return employee
def display_data(employee):
print('Employee code:', employee[0])
print('Employee name:', employee[1])
print('Salary:', employee[2])
print()
def write_record():
#open file in binary mode for writing.
outfile = open('emp1.dat', 'ab')
def read_records():
#open file in binary mode for reading
infile = open('emp1.dat', 'rb')
#read to the end of file.
while True:
try:
#reading the oject from file
employee = pickle.load(infile)
infile.close()
def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')
def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()
if choice == '1':
write_record()
else:
print('Invalid input')
main()
OUTPUT:
QUES 12: Create a module , length covertor.py which stores functions for various
length conversions.
ANSWER 12 :
CODE:
global ask2
ask2=""
def Help():
print('''
ENTER 1 FOR MILE TO KMs CONVERSION
ENTER 2 FOR KM TO MILES
ENTER 3 FEET TO INCHES
ENTER 4 FOR INCHES TO FEET ''')
main()
def main():
ask1=str(input("\nLENGTH CONVERTER\nType help to
know about the module,\nType y to continue with the
operation:"))
if ask1=="help":
Help()
elif ask1=="y":
ask2="yes"
print (ask2)
else:
print("wrong input")
main()
while ask2=="yes":
def Mile_to_KM():
mile_in=int(input("Enter length to be
converted(in miles):"))
con_km = mile_in*1.609344
print("Length in Kilometres:",con_km,"Km")
def KM_to_Mile():
km_in=int(input("Enter length to be
converted(in kilometres):"))
con_mile = km_in/1.609344
print("Length in Miles:",con_mile,"miles")
def Feet_to_Inches():
feet_in=int(input("Enter length to be
converted(in feet):"))
con_inch = feet_in*12
print("Length in Feet:",con_inch,"inches")
def Inches_to_Feet():
inch_in=int(input("Enter length to be
converted(in inches):"))
con_feet = inch_in/12
print("Length in Inches:",con_feet,"feet")
if ch==1:
Mile_to_KM()
elif ch==2:
KM_to_Mile()
elif ch==3:
Feet_to_Inches()
elif ch==4:
Inches_to_Feet()
else:
print("Wrong Input")
def main():
ask1=str(input("\nMASS CONVERTER\nType help to know
about the module,\nType y to continue with the
operation:"))
if ask1=="help":
Help()
elif ask1=="y":
ask2="yes"
print (ask2)
else:
print("wrong input")
main()
while ask2=="yes":
def kgtotonne( x ):
print("Value in tonne:",x *
one_kg_in_tonnes)
def tonnetokg( x ) :
print("Value in kilograms:",x /
one_kg_in_tonnes)
def kgtopound ( x ):
print("Value in pounds:",x *
one_kg_in_pound)
def poundtokg( x ) :
print("Value in kilograms:",x /
one_kg_in_pound)
ch=int(input("Enter your choice:"))
if ch==1:
var=int(input("Enter mass to be
converted(in kg):"))
kgtotonne(var)
elif ch==2:
var=int(input("Enter mass to be
converted(in tonne):"))
tonnetokg(var)
elif ch==3:
var=int(input("Enter mass to be
converted(in kg):"))
kgtopound (var)
elif ch==4:
var=int(input("Enter mass to be
converted(in pound):"))
poundtokg(var)
else:
print("Wrong Input")
ask2=str(input("Do you want to continue,yes or
no?"))
else:
pass
main()
OUTPUT:
QUES 14: Write a program to perform push and pop operations on a list
containing members like
as given in the following definition of item node.
Definition: MemberNo. (integer) , membername (string), age (integer)
ANSWER 14 :
CODE:
from sys import exit
stacklist = list()
def remover():
stacklist.pop (0)
def push():
stacklist.append(input("data to be entered is? \n\t>>"))
while True:
print(" 1. Push MEMBER In \n 2.Pop MEMBER \n 3.display \n 4.exit")
rec=['E_no','Name','Salary']
with open('e.csv','w',newline='') as f:
csv_w=csv.writer(f)
csv_w.writerow(rec)
for i in l:
csv_w.writerow(i)
print("File created")
def show():
with open('e.csv','r',newline='') as f:
csv_r=csv.reader(f)
for j in csv_r:
print(j)
while True:
print(''' Enter Choice
1. Insert records
2. Show Records
3. Exit''')
ch1=int(input("Choose Choice: "))
if ch1==1:
inrec()
elif ch1==2:
show()
elif ch1==3:
print("Ended")
break
else:
print("Invalid input")
OUTPUT:
Q16: Write a function to write data into binary file marks.dat and display the
records of students who scored more than 95 marks.
ANS 16:
CODE:
import pickle
def search_95plus():
f = open("marks.dat","ab")
while True:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Wnat more records?Yes:")
if ch.lower() not in 'yes':
break
f.close()
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2] > 95:
cnt += 1
print("Record:", cnt)
print("RollNO:", s[0])
print("Name:", s[1])
print("Marks:", s[2])
except Exception:
f.close()
search_95plus()
OUTPUT:
Q17: .Create a binary file client.dat to hold records like ClientID, Client name, and
Address using the dictionary. Write functions to write data, read them, and print on
the screen.
ANS17:
CODE:
import pickle
rec={}
def file_create():
f=open("client.dat","wb")
cno = int(input("Enter Client ID:"))
cname = input("Enter Client Name:")
address = input("Enter Address:")
rec={cno:[cname,address]}
pickle.dump(rec,f)
def read_data():
f = open("client.dat","rb")
print("*"*78)
print("Data stored in File. .. ")
rec=pickle.load(f)
for i in rec:
print(rec[i])
file_create()
read_data()
OUTPUT
Q18: . Write a program to replace all spaces from text with - (dash) from the file intro.txt
ANS 18:
CODE:
def program6():
cnt = 0
with open("intro.txt","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("intro.txt","w") as f1:
f1.write(data)
with open("intro.txt","r") as f1:
print(f1.read())
program6()
OUTPUT:
Q19: Write a program to count a total number of lines and count the total number
of lines starting with 'A', 'B', and 'C' from the file myfile.txt.
Ans 19:
CODE:
def program5():
with open("MyFile.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("Total Number of lines are:",cnt_lines)
print("Total Number of lines strating with A are:",cnt_A)
print("Total Number of lines strating with B are:",cnt_B)
print("Total Number of lines strating with C are:",cnt_C)
program5()
OUTPUT:
Q20: Write a program to create a binary file sales.dat and write a menu driven
program to do the following:
1. Insert record 2. Search Record 3. Update Record 4. Display record 5. Exit
Ans 20:
CODE:
import pickle
import os
def main_menu():
print("1. Insert a record")
print("2. Search a record")
print("3. Update a record")
print("4. Display a record")
print("5. Delete a record")
print("6. Exit")
ch = int(input("Enter your choice:"))
if ch==1:
insert_rec()
elif ch==2:
search_rec()
elif ch==3:
update_rec()
elif ch==4:
display_rec()
elif ch==5:
delete_rec()
elif ch==6:
print("Have a nice day!")
else:
print("Invalid Choice.")
def insert_rec():
f = open("sales.dat","ab")
c = 'yes'
while True:
sales_id=int(input("Enter ID:"))
name=input("Enter Name:")
city=input("Enter City:")
d = {"SalesId":sales_id,"Name":name,"City":city}
pickle.dump(d,f)
print("Record Inserted.")
print("Want to insert more records, Type yes:")
c = input()
c = c.lower()
if c not in 'yes':
break
main_menu()
f.close()
def display_rec():
f = open("sales.dat","rb")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open("sales.dat","rb")
s=int(input("Enter id to search:"))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["SalesId"]==s:
f1=1
print(d)
break
except Exception:
f.close()
if f1==0:
print("Record not found...")
else:
print("Record found...")
main_menu()
def update_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
s=int(input("Enter id to update:"))
try:
while True:
d = pickle.load(f1)
if d["SalesId"]==s:
d["Name"]=input("Enter Name:")
d["City"]=input("Enter City:")
pickle.dump(d,f2)
except EOFError:
print("Record Updated.")
f1.close()
f2.close()
os.remove("sales.dat")
os.rename("temp.dat","sales.dat")
main_menu()
def delete_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
s=int(input("Enter id to delete:"))
try:
while True:
d = pickle.load(f1)
if d["SalesId"]!=s:
pickle.dump(d,f2)
except EOFError:
print("Record Deleted.")
f1.close()
f2.close()
os.remove("sales.dat")
os.rename("temp.dat","sales.dat")
main_menu()
main_menu()
Output:
Q21 Write a MySQL connectivity program in Python to
• Create a database school
• Create a table students with the specifications - ROLLNO integer, STNAME
character(10) in MySQL and perform the following operations:
Answers 21
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",passwd="rojo",database='
school')
cn=db.cursor()
def insert_rec():
try:
while True:
rn=int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
gr=input("Enter grade:")
cn.execute("insert into students
values({},'{}',{},'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
break
except Exception as e:
print("Error", e)
def update_rec():
try:
rn=int(input("Enter rollno to update:"))
marks=float(input("Enter new marks:"))
gr=input("Enter Grade:")
cn.execute("update students set marks={},grade='{}' where
rno={}".format(marks,gr,rn))
db.commit()
except Exception as e:
print("Error",e)
def delete_rec():
try:
rn=int(input("Enter rollno to delete:"))
cn.execute("delete from students where rno={}".format(rn))
db.commit()
except Exception as e:
print("Error",e)
def view_rec():
try:
cn.execute("select * from students")
except Exception as e:
print("Error",e)
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4.
Display Record \n5. Exit")
ch=int(input("Enter your choice<1-4>="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print("Wrong option selected")
OUTPUT:
OUTPUT
SQL
COMMANDS
COMMAND 1:- SHOW DATABASES
COMMAND 2 & 3:- CREATE DATABASE
& USE DATABASE
COMMAND 4:- SHOW TABLES
COMMAND 5 & 6:- CREATE AND DESC
TABLE
COMMAND 7 & 8:- INSERT AND
SELECT
COMMAND 9:- ALTER TABLE: ADD
COMMAND 10:- ALTER TABLE-DROP
COMMAND 11:- SELECT-LIKE QUERY
COMMAND 12:- SELECT -ORDER BY
COMMAND 13 :-DISTINCT
COMMAND 14 :-IN & NOT IN
COMMAND 15:- GROUPING FUNCTIONS-
MAX, MIN, AVG, SUM, COUNT
COMMAND 16:- UPDATE RECORD
COMMAND 17:- SELECT- GROUP BY
COMMAND 18:- SELECT-HAVING CLAUSE
COMMAND 19:- SELECT-ADDING TEXT
COMMAND 20:- DELETE RECORD
COMMAND 20 & 21:- TRUNCATE TABLE
AND DROP TABLE
COMMAND 22:- DROP DATABASE