Practical File
Practical File
This is certified to be the bona fide work of the student in the Computer
Laboratory during the academic year 2020-21.
Number of Practicals certified 40 out of 40 in the subject of Computer
Science.
7 Python program to simulate a dice using user defined function. The program
should keep generating random number until user prompts to stop. 11
8 Python program to implement python mathematical functions. 12
9 Python program to implement python string functions. 13
10 Python program to make user define module and import same in another module or 14
program.
11 Python program to read and display file content line by line with each word 15
separated by #.
12 Python program to remove all the lines that contain the character ‘a’ in a file and
write it to another file 16
13 python program to read characters from keyboard one by one, all lower case letters 17
gets stored inside a file “LOWER”, all uppercase letters gets stored inside a file
“UPPER” ,and all other characters get stored inside “OTHERS”.
14 Python program to create a binary file with name and roll number. Search for a 18
given roll number and display name, if not found display appropriate message.
15 Python program to create a binary file with roll number, name and marks, input a 19
roll number and update the marks.
16 Python program to create a CSV file with empid, name and mobile no. and search 20
empid, update the record and display the records.
17 Python program to create Lpush( ) and Lpop( ) function to do push and pop 21
operation on a stack using a list e.g. take a student information and push and pop
the details.
18 Python program to perform insert and delete operations on a Queue containing 22-
numbers as a list. 23
19 Create a student table and insert data. Implement the following SQL commands on 24-
the student table: ALTER table to add new attributes / modify data type / drop 25
attribute. UPDATE table to modify data ORDER By to display data in
ascending/descending order. DELETE to remove tuple(s) GROUP BY and find the
min, max, sum, count and average.
Write SQL commands for the statements (i) to (iv) and give outputs for the SQL
queries (v) to (viii)
20 Table: Activity
ACode ActivityName ParticipantsNum PrizeMoney ScheduleDate
1001 Relay 100x4 16 10000 23-Jan-2004
1002 High Jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004 26-
1005 Long Jump 12 9000 01-Jan-2004 27
1008 Discuss 10 15000 19-Mar-2004
Throw
Table: Coach
PCode Name ACode
1 Ahmad Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
0. To display the name of all activities with their ACodes in descending order.
i. To display sum of PrizeMoney for each of the Number of Participants
groupings.
ii. To display the coach’s name and ACodes in ascending order of ACode
from the table Coach.
iii. To display the content of the Activity table whose ScheduleDate earlier
than 01/01/2004 in ascending order of ParticipantNum.
iv. Select Count(Distinct ParticipantsNum) From Activity
v. Select Max(ScheduleDate),Min(ScheduleDate) From Activity;
vi. Select Sum(PrizeMoney) From Activity;
vii. Select Distinct ParticipantsNum from coach;
Integrate SQL with Python by importing the MySQL module record of employee 28
21 and display the record.
Integrate SQL with Python by importing the MySQL module to search an 29
22 employee using empno and if present in table display the record, if not display
appropriate method.
23 Integrate SQL with Python by importing the MySQL module to search a student 30
using rollno, update the record.
24 Integrate SQL with Python by importing the MySQL module to search a student 31
using rollno, delete the record.
Write a menudriven program to integrate SQL with Python by importing MySQL 32-
module to perform the following operations: 33
25 1 ) Create table student
2) Insert record into student
3 ) Update records
4) Delete record
26 Take a sample of ten phishing e-mails (or any text file) and find most commonly 34
occurring word(s)
1. Write a python program to search an element in a list and display the frequency
of element present in list and their location using Linear search by using user
defined function. [List and search element should be entered by user]
CODE:
list1=input(“enter a list:”)
listo=list(list1)
print(‘the original list is’,listo)
n=input(“enter element whose frequency is to be calculated:”)
def func(x,l):
if x in l:
print(“element found!!”)
else:
print(“oops! Not found”)
print(“frequency of the entered element is:”,l.count(x))
print(‘index of the element is:’,l.index(x’)
func(n,list1)
OUTPUT:
2. Write a python program to search an element in a list and display the frequency
of element present in list and their location using binary search by using user
defined function. [List and search element should be entered by user]
CODE:
def func(x,l):
low=0
high=len(l)-1
Found=False
while low<=high and not Found:
mid=(low+high)//2
if x==l[mid]:
Found=True
elif x>l[]mid:
low=mid+1
else:
high=mid+1
if Found==True:
print(‘element is found!!’)
else:
print(‘element is not found!’)
OUTPUT:
3. Write a python program to pass list to a function and double the odd values and
half even values of a list and display list element after changing.
CODE:
def func(a):
n=[i/2 for i in a if i%2==0]
o=[i*2 for i in a if i%2!=0]
print(“the list after the halving the even elements and doubling the odd ones:”)
print(n+o)
list1=[144,22,1,299,13]
print(“the original list is:”,list1)
func(list1)
OUTPUT:
4. Write a Python program input n numbers in tuple and pass it to function to count
how many even and odd numbers are entered.
CODE:
numbers=(54,55,69,789,592,11,222)
print(“the tuple is:“,numbers)
def func(x):
count_even=0
count_odd=0
for i in x:
if not i % 2:
count_even+=1
else:
count_odd+=1
print(“number of even numbers:”,count_even)
print(“the number of odd numbers,count_odd”)
OUTPUT:
:
5. Write a Python program to function with key and value, and update value at that
key in dictionary entered by user.
CODE:
d={1:'one',2:'two'}
print('the original dictionary is:',d)
def fun(x):
key=int(input('enter key number that you want to add:'))
value=str(input("enter value of the specified key:"))
d1={key:value}
x.update(d1)
print("the updated dictionary is:",x)
fun(d)
OUTPUT:
6.Write a Python program to pass a string to a function and count how many
vowels present in the string.
CODE:
s=("have unwavering faith")
print("the original string is:",s)
def f(v):
vowels=0
for i in v:
if(i=="a" or i=='i'or i=='e' or i=='o' or i=='u'):
vowels+=1
print("the number of vowels in the string are:",vowels)
f(s)
OUTPUT:
7. Write a Python program to simulate a dice (Generate a random no between1 to
6) using user defined function. The program should keep generating random
number until user prompts to stop.
CODE:
import random
n=int(input('enter the number of times you wanna roll the dice:'))
for i in range(n):
print(random.randint(1,6))
OUTPUT:
OUTPUT:
CODE:
s=(“akshata”)
print(“the original string:”,s)
def f(x):
return x[0:2]+x[-2:]
print(“the string of the first and last 2 characters:”,f(s))
OUTPUT:
10. Write a python program to make user define module and import same in
another module or program. (import <modulename> and from <module name>
import <function name>)
CODE:
a)creating the module with the name 'cs.py'
def myfunc():
print(“I love computer science.”)
and save it with .py extension.
OUTPUT:
11. Write a python program to read and display file content line by line with each
word separated by #.
CODE:
file=open("projo.txt","r")
for i in file:
a=(file.read())
print('original file is:',a)
for r in a:
print(r+'#')
OUTPUT:
12. Write a python program to remove all the lines that contain the character ‘a’ in
a file and write it to another file.
CODE:
file=open("projo.txt")
file1=open("mojo.txt","w")
for i in file:
if "a" in i:
i=i.replace('.','')
else:
file1.write(i)
file1.flush()
file.close()
file1.close()
OUTPUT:
13. Write a python program to read characters from keyboard one by one, all lower
case letters gets stored inside a file “LOWER”, all uppercase letters gets stored
inside a file “UPPER” ,and all other characters get stored inside “OTHERS”
CODE:
f1=open("lower.txt","w")
f2=open("upper.txt","w")
f3=open("others.txt","w")
c=True
while c:
c=input("enter any character of the keyboard or False to terminate:")
if c=="False":
break
elif c.islower():
f1.write(c)
elif c.islower():
f2.write(c)
else:
f3.write(c)
f1.flush()
f2.flush()
f3.flush()
f1.close()
f2.close()
f3.close()
OUTPUT:
in shell
in files
CODE:
import pickle
import sys
sdata={}
def write():
file=open('studentss.txt','ab')
n=int(input('enter no of students:'))
for i in range(n):
print("details of students",i+1)
sdata['rollno']= int(input("enter roll no:"))
sdata['name']=input('enter name:')
pickle.dump(sdata,file)
file.close()
def display():
file=open("studentss.txt",'rb')
try:
while True:
lama=pickle.load(file)
print(lama)
except EOFError:
pass
file.close()
def search():
file=open("studentss.txt","rb")
rn=int(input("enter value to be searched:"))
found=0
try:
while True:
d=pickle.load(file)
if d['rollno']==rn:
print('the searched record is:')
print(d)
found=1
break
except EOFError:
pass
if found==0:
print("oops!! record not found")
file.close()
while True:
print("MENU\n 1-fun \n 2-display")
print("3-search \n 4-exit \n")
a=int(input("enter choice serially:"))
if a==1:
write()
if a==2:
display()
if a==3:
search()
if a==4:
print("have a good day. bye!!!")
sys.exit
OUTPUT:
15. Write a python program to create a binary file with roll number, name and
marks, input a roll number and update the marks.
CODE:
import pickle
sdata={}
n=int(input('enter no of students:'))
file=open('student.txt','ab')
for i in range(n):
print("details of students",i+1)
sdata['rollno']= int(input("enter roll no:"))
sdata['name']=input('enter name:')
sdata['marks']=float(input('enter marks:'))
pickle.dump(sdata,file)
sdata={}
file.close()
file=open("student.txt",'rb')
try:
while True:
sdata=pickle.load(file)
print(sdata)
except EOFError:
file.close()
find=False
rno=int(input("enter roll no to be searched:"))
file=open("student.txt","rb+")
try:
while True:
p=file.tell()
sdata=pickle.load(file)
if sdata['rollno']==rno:
sdata['marks']=float(input("enter updated marks:"))
file.seek(p)
pickle.dump(sdata,file)
find=True
except EOFError:
if (find==True):
print("yay!! data has been updated!")
else:
print("oops!! invalid data enetered, kindly retry!")
file.close()
file=open("student.txt","rb")
try:
while True:
sdata=pickle.load(file)
print(sdata)
except EOFError:
file.close
OUTPUT:
16. Write a python program to create a CSV file with empid, name and mobile no.
and search empid, update the record and display the records.
CODE:
import csv
empid=int(input("Enter the id:"))
empname=input("Enter the name:")
empno=int(input("Enter the number:"))
row=[]
fields=[empid,empname,empno]
with open("EMployee.csv",'w',newline='') as csv_file:
writer=csv.writer(csv_file,delimiter=',')
writer.writerow(fields)
for i in row:
writer.writerow(i)
print('CSV FILE WRITTEN')
with open("EMployee.csv",'r') as csv_file:
reader=csv.reader(csv_file)
rows=[]
for r in reader:
rows.append(r)
print(r)
with open('EMployee.csv','r') as csv_file:
reader=csv.reader(csv_file)
Empid=int(input('Enter a empid whose record is to be searched:'))
for rec in reader:
if rec[0]==Empid:
print(rec)
print("RECORD FOUND IS ",rec)
text = open("EMployee.csv", "r+")
text = ''.join([i for i in text])
Empid=int(input("Enter id to be updated:"))
Empname=input("Enter the name to be updated:")
EmpNumber=int(input("Enter mob_no to be updated:"))
text = text.replace(empname, Empname)
text = text.replace(str(empid), str(Empid))
text = text.replace(str(empno), str(EmpNumber))
print("Record Updated successfully")
print(text)
OUTPUT:
OUTPUT:
18.Python program to perform insert and delete operations on a Queue containing
numbers as a list.
CODE:
def enqueue(q,x):
q.append(x)
def dequeue(q):
global front
t=q[front]
front+=1
return t
list=[1,2,3,4,5]
print("THE ORIGINAL LIST:")
print(list)
front=0
enqueue(list,92)
print("THE LIST AFTER INSERTING:")
print(list)
a=dequeue(list)
print("ELEMENT DELETED:")
print(a)
OUTPUT:
19. Create a student table and insert data. Implement the following SQL commands
on the student table:
ALTER table to add new attributes / modify data type / drop attribute
UPDATE table to modify data ORDER By to display data in ascending /
descending order
DELETE to remove tuple(s) GROUP BY and find the min, max, sum, count and
average
CODE:
create,insert and alter commands:
update, order by, delete and group by commands:
i.To display the name of all activities with their ACodes in descending order.
ii.To display sum of PrizeMoney for each of the Number of Participants groupings.
iii.To display the coach’s name and ACodes in ascending order of ACode from the table Coach.
iv.To display the content of the Activity table whose ScheduleDate earlier than 01/01/2004 in
ascending order of ParticipantNum.
v.Select Count(Distinct ParticipantsNum) From Activity
vi.Select Max(ScheduleDate),Min(ScheduleDate) From Activity;
vii.Select Sum(PrizeMoney) From Activity;
vii.Select Distinct ParticipantsNum from coach;
CODE:
OUTPUT:
21. Integrate SQL with Python by importing the MySQL module record of
employee and display the record.
CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host='localhost',user='root',passwd='akki',database='department')
if mycon.is_connected():
print("successfully")
c=mycon.cursor()
a='select * from EMPLOYEE'
c.execute(a)
for u in c:
print(u)
mycon.commit()
OUTPUT:
22. Integrate SQL with Python by importing the MySQL module to search an
employee using empno and if present in table display the record, if not display
appropriate method.
CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host='localhost',user='root',passwd='akki',database='department')
if mycon.is_connected():
print("successfully")
c=mycon.cursor()
i=1
while i<4:
print('1. CREATE , 2. INSERT , 3. DISPLAY')
a=int(input("enter your choice:"))
if a==1:
c.execute(" CREATE TABLE EMPLOYE112( EMPNO INT(10), EMPNAME VARCHAR(20), EMPSAL
INT(100))")
print("created")
elif a==2:
EMPNO=int(input('enter id:'))
EMPNAME=input('enter name:')
EMPSAL=int(input('enter salary:'))
S="INSERT INTO EMPLOYE112(EMPNO,EMPNAME,EMPSAL)VALUES({},'{}',
{})".format(EMPNO,'EMPNAME',EMPSAL)
c.execute(S)
print("record inserted!")
mycon.commit()
elif a==3:
EMPID=int(input('enter id to be searched:'))
e='select EMPNAME from EMPLOYE112 WHERE EMPNO={}'.format(EMPID)
c.execute(e)
for u in c:
if u==True:
print(u)
else:
print("record not found!")
mycon.commit()
OUTPUT:
CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host='localhost',user='root',passwd='akki',database='department')
if mycon.is_connected():
print("successfully")
c=mycon.cursor()
i=1
while i<4:
print('1. UPDATE , 2. DISPLAY')
a=int(input("enter your choice:"))
if a==2:
c.execute(" SELECT * FROM STUDENT")
for y in c:
print(y)
mycon.commit()
elif a==1:
s='UPDATE STUDENT SET ROLLNO=14 WHERE ROLLNO=4'
c.execute(s)
print("record updated!!!")
OUTPUT:
24. Integrate SQL with Python by importing the MySQL module to search a
student using rollno, delete the record.
CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host='localhost',user='root',passwd='akki',database='department')
if mycon.is_connected():
print("successfully")
c=mycon.cursor()
i=1
while i<2:
print('1. DELETE , 2. DISPLAY, 3. DISPLAY FULL TABLE' )
a=int(input("enter your choice:"))
if a==1:
c.execute(" DELETE FROM STUDENT WHERE ROLLNO=2")
print("record deleted")
elif a==2:
s=' SELECT * FROM STUDENT WHERE ROLLNO=1'
c.execute(s)
for y in c:
print(y)
print("record not present")
elif a==3:
c.execute(' SELECT * FROM STUDENT')
for l in c:
print(l)
mycon.commit()
OUTPUT:
25. Write a menudriven program to integrate SQL with Python by importing MySQL module to
perform the following operations:
1 ) Create table student
2) Insert record into student
3 ) Update records
4) Delete record
CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host='localhost',user='root',passwd='akki',database='shoe_shop')
if mycon.is_connected():
print("successfully")
c=mycon.cursor()
i=1
while i<2:
print("MENU:")
print('1.CREATE 2. INSERT 3. UPDATE 4. DELETE 5. DISPLAY' )
print(" ")
a=int(input("enter your choice:"))
if a==4:
c.execute(" DELETE FROM STUDENT WHERE ROLLNO=2")
print("record deleted")
elif a==3:
RN=int(input("enter rollno that you want to update:"))
rn=int(input("enter the NEW rollno:"))
s='UPDATE STUDENT SET ROLLNO={} WHERE ROLLNO={}'.format(rn,RN)
c.execute(s)
for y in c:
print(y)
print("record updated!")
elif a==5:
c.execute(' SELECT * FROM STUDENT')
for l in c:
print(l)
mycon.commit()
elif a==2:
ROLLNO=int(input('enter ROLLNO:'))
NAME=input('enter name:')
MARKS=int(input('enter MARKS:'))
S="INSERT INTO STUDENT(ROLLNO,NAME,MARKS)VALUES({},'{}',
{})".format(ROLLNO,NAME,MARKS)
c.execute(S)
print("record inserted!")
mycon.commit()
elif a==1:
c.execute(" CREATE TABLE STUDENT( ROLLNO INT(10), NAME VARCHAR(20),
MARKS INT(100))")
print("created")
OUTPUT:
26. Take a sample of ten phishing e-mails (or any text file) and find most
commonly occurring word(s)
CODE:
from collections import Counter
#ten phishing mails taken as examples
OUTPUT: