0% found this document useful (0 votes)
74 views38 pages

Samrat CSPracticalFile

The document contains a practical file for computer science experiments in Python. It lists 20 experiments covering topics like file handling, data structures, SQL integration, and mathematical functions. Each experiment is given a page number and includes a brief description of the task and sample code to implement the solution. The file provides a set of practical exercises for students to practice and learn Python concepts.

Uploaded by

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

Samrat CSPracticalFile

The document contains a practical file for computer science experiments in Python. It lists 20 experiments covering topics like file handling, data structures, SQL integration, and mathematical functions. Each experiment is given a page number and includes a brief description of the task and sample code to implement the solution. The file provides a set of practical exercises for students to practice and learn Python concepts.

Uploaded by

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

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("AI.txt","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()

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("AI.txt","r")
content=file.read()
vowels=0

consonants=0
lower_case=0
upper_case=0
for ch in content:
if(ch.islower()):
lower_case+=1
elif(ch.isupper()):
upper_case+=1
ch=ch.lower()
if(ch in ['a','e','i','o','u']):
vowels+=1
else:
consonants+=1
file.close()
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 ('StudentRecord1.dat','ab') as Myfile:


srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(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 ('StudentRecord1.dat','rb') as Myfile:
while True:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:

print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])

def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')

print('2.Search Records (By Roll No)')


print('0.Exit (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 ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,

"SREMARKS":sremark}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(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 ('StudentRecord.dat','rb') as Myfile:

6
newRecord=[]
while True:
try:

rec=pickle.load(Myfile)
newRecord.append(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 ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)

def main():
while True:
print('\nYour Choices are: ')

print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')

7
print('0.Exit (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("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:

if 'a' not in line:


f2.write(line)
print('File Copied Successfully! \nContent without a: \n')
f1.close()
f2.close()

f2 = open("copyMydoc.txt","r")
print(f2.read())

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 (random.randint(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)+":"))
mylst.append(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):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
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

1.push
2.pop
3.peek
4.display
5.exit''')
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):
qLst.append(val)
if len(qLst)==1:
front=rear=0
else:
rear=len(qLst)-1

def Dqueue(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
val = qLst.pop(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('emails.txt','r')

a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(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 = collections.Counter(d)
for word, count in word_counter.most_common(n):

print(word, ": ", count)


fin.close()

#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=csv.writer(csvf,delimiter=',')

choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
writecsv.writerow([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=csv.reader(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 = csv.reader(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(math.pow(2,8)))
print("Square root of 625=" +str(math.sqrt(625)))
print("5^e="+str(math.exp(5)))
print("log(625),base 5="+str(math.log(625,5)))
print("Floor value of 6.25="+str(math.floor(6.25)))
print("Ceiling value of 6.25="+str(math.ceil(6.25)))
print('Absolute value of -95 and 55=',str(math.fabs(-95)),str(math.fabs(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 package.py
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 mysql.connector
con = mysql.connector.connect(host="localhost", user='root', password="",
database="employee")
cur=con.cursor()

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)


cur.execute(query)
con.commit()

print("row inserted successfully...")

ch=input("Do You Want to enter more records?(y/n)")


if ch"n":

break

cur.execute("select * from employee")


data=cur.fetchall

for i in data:
print(i)

print("Total number of rows retrieved=",cur.rowcount)

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 mysql.connector as mycon con =
mycon.connect(host='localhost',user='root',password="",database="company")
cur = con.cursor()

print("#"*40)
print("EMPLOYEE SEARCHING FORM")

print("#"*40)

print("\n\n")

ans='y'

while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select from employee where empno=()".format(eno)
cur.execute(query)

result = cur.fetchall()
if cur.rowcount==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 mysql.connector as mycon con =
mycon.connect(host='localhost',user='root',password="",database="company")
cur = con.cursor()

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)
cur.execute(query)

result=cur.fetchall()
if cur.rowcount==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 choice.lower()=='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)
cur.execute(query)
con.commit()

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 mysql.connector as mycon con =
mycon.connect(host='localhost',user='root',password="",database="company")
cur = con.cursor()

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)
cur.execute(query)

result=cur.fetchall()
if cur.rowcount==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 choice.lower()=='y':

query="DELETE FROM employee WHERE empno={}".format(empno)


cur.execute(query)
con.commit()
print("===RECORD DELETED SUCCESSFULLY!===")

ans=input("DELETE MORE?(Y):")

Output

36
37

You might also like