Computer Science
Practical File
Samrat Gaur
S. No. Experiment Name Page No.
1 Write a python program to read a text file line by line and display each word separated 2
by a '#'.
2 Write a python program to read a text file and display the number of 3
vowels/consonants/upper case/ lower case characters.
3 Write a python program to create a binary file with name and roll no and perform 4
search based on roll number.
4 Write a python program to create a binary file with name, roll no, marks and update 6
the marks using their roll numbers.
5 Write a python program to remove all the lines that contain the character 'a' in a file 9
and write it to another file.
6 Write a random number generator that generates random numbers between 1 and 6 10
(simulates a dice).
7 Write a python program using function to find the factorial of a natural number. 11
8 Write a python program using function to find the sum of all elements of a list. 12
9 Write a python program using function to compute the nth Fibonacci number. 13
10 Write a python program to implement a Stack using a list data structure. 14
11 Write a python program to implement a Queue using a list data structure. 19
12 Take a sample of ten phishing e-mails (or any text file) and find the most commonly 23
occurring words using python program.
13 Write a python program to create a CVS file with name and roll number and perform 25
search for a given roll number and display the name.
14 Write a python program to implement python mathematical functions. 27
15 Write a python program to make user defined module and import same in another 28
module or program.
16 Write a python program to implement python string functions. 29
17 Write a python program to integrate SQL with python by importing the MySQL 30
module and create a record of employee and display the record.
18 Write a python program to integrate SQL with python by importing the MySQL 32
module to search an employee number and display record, if empno not found display
appropriate message.
19 Write a python program to integrate SQL with python by importing the MySQL 34
module to update the employee record of entered empno.
20 Write a python program to integrate SQL with python by importing the MySQL 36
module to delete the employee record of entered employee number.
1
Program 1
Write a python program to read a text file line by line and display each word separated by a '#'.
Code
file=open("[Link]","r")
lines=[Link]()
for line in lines:
words=[Link]()
for word in words:
print(word+"#",end="")
print("")
[Link]()
Output
2
Program 2
Write a python program to read a text file and display the number of vowels/consonants/upper case/ lower
case characters.
Code
file=open("[Link]","r")
content=[Link]()
vowels=0
consonants=0
lower_case=0
upper_case=0
for ch in content:
if([Link]()):
lower_case+=1
elif([Link]()):
upper_case+=1
ch=[Link]()
if(ch in ['a','e','i','o','u']):
vowels+=1
else:
consonants+=1
[Link]()
print("Number of vowels are: ",vowels)
print("Number of consonants are: ", consonants)
print("Number of lower case letters are: ", lower_case)
print("Number of upper case letters are: ", upper_case)
Output
3
Program 3
Write a python program to create a binary file with name and roll no and perform search based on roll
number.
Code
import pickle
def Writerecord(sroll,sname):
with open ('[Link]','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
[Link](srecord,Myfile)
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('[Link]','rb') as Myfile:
while True:
rec=[Link](Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
def main():
while True:
print('\nYour Choices are: ')
print('[Link] Records')
print('[Link] Records (By Roll No)')
print('[Link] (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
4
if ch==1:
Input()
elif ch==2:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
Output
5
Program 4
Write a python program to create a binary file with name, roll no, marks and update the marks using their
roll numbers.
Code
def Writerecord(sroll,sname,sperc,sremark):
with open ('[Link]','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
[Link](srecord,Myfile)
def Readrecord():
with open ('[Link]','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=[Link](Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('[Link]','rb') as Myfile:
6
newRecord=[]
while True:
try:
rec=[Link](Myfile)
[Link](rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('[Link]','wb') as Myfile:
for j in newRecord:
[Link](j,Myfile)
def main():
while True:
print('\nYour Choices are: ')
print('[Link] Records')
print('[Link] Records')
print('[Link] Records')
7
print('[Link] (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()
Output
8
Program 5
Write a python program to remove all the lines that contain the character 'a' in a file and write it to another
file
Code
f1 = open("[Link]")
f2 = open("[Link]","w")
for line in f1:
if 'a' not in line:
[Link](line)
print('File Copied Successfully! \nContent without a: \n')
[Link]()
[Link]()
f2 = open("[Link]","r")
print([Link]())
Output
9
Program 6
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Code
import random
import random
def roll_dice():
print ([Link](1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
Output
10
Program 7
Write a python program using function to find the factorial of a natural number
Code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
n = int(input("Enter any number: "))
print("The factorial of given number is: ",factorial(n))
main()
Output
11
Program 8
Write a python program using function to find the sum of all elements of a list.
Code
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)
mylst = []
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
[Link](n)
sum = lstSum(mylst,len(mylst))
print("Sum of List items ",mylst, " is :",sum)
Output
12
Program 9
Write a python program using function to compute the nth Fibonacci number.
Code
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))
nterms = int(input("Please enter the Range Number: "))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')
Output
13
Program 10
Write a python program to implement a Stack using a list data structure.
Code
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
[Link](item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=[Link]()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
14
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
def main():
stk=[]
top=None
while True:
print('''stack operation
[Link]
[Link]
[Link]
[Link]
[Link]''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
15
elif choice==5:
break
else:
print('invalid')
exit()
main()
Output
16
17
18
Program 11
Write a python program to implement a Queue using a list data structure.
Code
def isEmpty(qLst):
if len(qLst)==0:
return 1
else:
return 0
def Enqueue(qLst,val):
[Link](val)
if len(qLst)==1:
front=rear=0
else:
rear=len(qLst)-1
def Dqueue(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
val = [Link](0)
if len(qLst)==0:
front=rear=None
return val
def Peek(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
front=0
return qLst[front]
def Display(qLst):
if isEmpty(qLst):
19
print("No Item to Dispay in Queue....")
else:
tp = len(qLst)-1
print("[FRONT]",end=' ')
front = 0
i = front
rear = len(qLst)-1
while(i<=rear):
print(qLst[i],'<-',end=' ')
i += 1
print()
def main():
qList = []
front = rear = 0
while True:
print()
print("##### QUEUE OPERATION #####")
print("1. ENQUEUE ")
print("2. DEQUEUE ")
print("3. PEEK ")
print("4. DISPLAY ")
print("0. EXIT ")
choice = int(input("Enter Your Choice: "))
if choice == 1:
ele = int(input("Enter element to insert"))
Enqueue(qList,ele)
elif choice == 2:
val = Dqueue(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("\n Deleted Element was : ",val)
20
elif choice==3:
val = Peek(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("Item at Front: ",val)
elif choice==4:
Display(qList)
elif choice==0:
print("Good Luck......")
break
main()
Output
21
22
Program 12
Take a sample of ten phishing e-mails (or any text file) and find the most commonly occurring words using
python program.
Code
def Read_Email_File():
import collections
fin = open('[Link]','r')
a= [Link]()
d={ }
L=[Link]().split()
for word in L:
word = [Link](".","")
word = [Link](",","")
word = [Link](":","")
word = [Link]("\"","")
word = [Link]("!","")
word = [Link]("&","")
word = [Link]("*","")
for k in L:
key=k
if key not in d:
count=[Link](key)
d[key]=count
n = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n))
word_counter = [Link](d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
[Link]()
#Driver Code
def main():
Read_Email_File()
main()
23
Output
24
Program 13
Write a python program to create a CVS file with name and roll number and perform search for a given roll
number and display the name.
Code
import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=[Link](csvf,delimiter=',')
choice='y'
while [Link]()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
[Link]([rl,n])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n).....")
with open('Student_Details.csv','r',newline='') as fileobject:
readcsv=[Link](fileobject)
for i in readcsv:
print(i)
import csv
number = input('Enter number to find: ')
found=0
with open('Student_Details.csv') as f:
csv_file = [Link](f, delimiter=",")
for row in csv_file:
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")
25
Output
26
Program 14
Write a python program to implement python mathematical functions.
Code
import math
print("2 raised to the 8th power=" +str([Link](2,8)))
print("Square root of 625=" +str([Link](625)))
print("5^e="+str([Link](5)))
print("log(625),base 5="+str([Link](625,5)))
print("Floor value of 6.25="+str([Link](6.25)))
print("Ceiling value of 6.25="+str([Link](6.25)))
print('Absolute value of -95 and 55=',str([Link](-95)),str([Link](55)))
Output
27
Program 15
Write a python program to make user defined module and import same in another module or program.
Code
def Square():
number=int(input("Enter the number: "))
area=number*number
print("Area of square= ", area)
def Rectangle():
l=int(input("Enter the length: "))
b=int(input("Enter the breadth: "))
area=l*b
print("Area of rectangle= ",area)
import package
import [Link]
import usermodule
from usermodule import Area_square,Area_rect
print(Area_square.Square())
print(Area_rect.Rectangle())
Output
28
Program 16
Write a python program to implement python string functions.
Code
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
Output
29
Program 17
Write a python program to integrate SQL with python by importing the MySQL module and create a record
of employee and display the record.
Code
import [Link]
con = [Link](host="localhost", user='root', password="",
database="employee")
cur=[Link]()
while True:
Eno=int(input("Enter Employee Number:"))
Name=input("Enter Employee Name:")
salary=float(input("Enter Employee Salary:"))
query="Insert into employee values({},'{}',{})".format(Eno,Name,salary)
[Link](query)
[Link]()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
if ch"n":
break
[Link]("select * from employee")
data=[Link]
for i in data:
print(i)
print("Total number of rows retrieved=",[Link])
Output
30
31
Program 18
Write a python program to integrate SQL with python by importing the MySQL module to search an
employee number and display record, if empno not found display appropriate message.
Code
import [Link] as mycon con =
[Link](host='localhost',user='root',password="",database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while [Link]()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select from employee where empno=()".format(eno)
[Link](query)
result = [Link]()
if [Link]==0:
print("Sorry! Empno not found")
else:
print("%10s" % "EMPNO", "%20s" % "NAME","%15s" % "DEPARTMENT","%10s" %
"SALARY")
for row in result:
print("%10s" %row[0],"%20"%row[1], "%15s" %row[2],"%10s" %row[3])
ans=input("SEARCH MORE (Y):")
Output
32
33
Program 19
Write a python program to integrate SQL with python by importing the MySQL module to update the
employee record of entered empno.
Code
import [Link] as mycon con =
[Link](host='localhost',user='root',password="",database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
eno=int(input("Enter empno to update: "))
query="SELECT * FROM employee WHERE empno={}".format(eno)
[Link](query)
result=[Link]()
if [Link]==0:
print("Sorry! Empno not found.")
else:
print("%10s" % "EMPNO", "%20s" % "NAME","%15s" % "DEPARTMENT","%10s" %
"SALARY")
for row in result:
print("%10s" %row[0],"%20"%row[1], "%15s" %row[2],"%10s" %row[3])
choice=input("Are you sure you want to update?(Y)")
if [Link]()=='y':
print("==You can update the details==")
d =input("Enter new department:")
if d=="":
d=row[2]
try:
n=input("Enter new name:")
s=input("Enter new salary:")
except:
s=row[3]
34
query="UPDATE employee SET name='{}',dept='{}' salary={} WHERE
empno={}".format(n,d,s,empno)
[Link](query)
[Link]()
print("##RECORD UPDATED##")
ans=input("Do you want to update more?(Y):")
Output
35
Program 20
Write a python program to integrate SQL with python by importing the MySQL module to delete the
employee record of entered employee number.
Code
import [Link] as mycon con =
[Link](host='localhost',user='root',password="",database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
eno=int(input("ENTER EMPNO TO DELETE: "))
query="SELECT * FROM employee WHERE empno={}".format(eno)
[Link](query)
result=[Link]()
if [Link]==0:
print("Sorry! Empno not found.")
else:
print("%10s" % "EMPNO", "%20s" % "NAME","%15s" % "DEPARTMENT","%10s" %
"SALARY")
for row in result:
print("%10s" %row[0],"%20"%row[1], "%15s" %row[2],"%10s" %row[3])
choice=input("ARE YOU SURE YOU ANT TO DELETE?(Y)")
if [Link]()=='y':
query="DELETE FROM employee WHERE empno={}".format(empno)
[Link](query)
[Link]()
print("===RECORD DELETED SUCCESSFULLY!===")
ans=input("DELETE MORE?(Y):")
Output
36
37