Professional Documents
Culture Documents
COMPUTER SCIENCE
PRACTICAL PROGRAMS
1|Page
2020 - 21
COMPUTER SCIENCE
PRACTICAL PROGRAMS
Signature: Signature:
Date: Date:
2|Page
2020 - 21
INDEX
SR.NO PROGRAM NAME PAGE NO
6 Program to find number of upper and lower case letters from the given string 10
and also demonstrate built in string functions.
11
7 Program to create a list to perform slicing and built in functions.
12
8 Program to create a tuple and perform tuple slicing.
13
9 Program to find the square root of the numbers by creating a list of numbers.
10 Program to find the area, circumference of the circle and the area, perimeter 14 – 15
of the rectangle by using functions for circle and rectangle operation.
16
11 Program of to find the Factorial of a given number using recursion.
17 – 18
12 Program to read, write and append the text file.
19
13 Program to write (dump) and read (load) the binary file.
20
14 Program to copy the content from a file and write on the other.
21
15 Program to capitalize the first 'n' letter of sentence.
22
16 Program to find the time taken using simple and recursion method of sum.
17 Program to add, delete and display the records of an Employee using stack 23 – 24
list.
18 Program to add, delete and display the records of an Employee using Queue 25 – 26
list.
3|Page
2020 - 21
23 Python program that takes a list of words and return the length of the 31
longest.
24 Python program to capitalize first and last letter of each word of a given 32
string.
30 Program to read record from a file "student.dat" using search method by roll 38
no.
31 Program to implement data insert, modify, search, display and delete using 39-42
dictionary (menu Driven).
43
32 Python program to count the number of record present in "student.csv" File.
44
33 Python program to print record in the form of comma separated values.
45
34 Python program to search record for given student name from csv file.
46
35 Program to write student data onto a csv file importing the cav module.
47
36 Program to write student data onto a csv file importing the cav module.
4|Page
2020 - 21
PROGRAM: 1
#Program to input user information
#Demonstration of if-elif condition
#Demonstrate arithmetic functions
OUTPUT:
5|Page
2020 - 21
PROGRAM: 2
def sum(a,b):
print ('The sum is: ',a+b)
def sub(a,b):
print ('The difference is: ',a-b)
defmult(a,b):
print ('The product is: ',a*b)
def div(a,b):
print ('The quotient is: ',a/b)
x=float(input('Enter the number: '))
y=float(input('Enter the number: '))
sum(x,y)
sub(x,y)
mult(x,y)
div(x,y)
OUTPUT:
6|Page
2020 - 21
PROGRAM: 3
#Program that prints the table of any number using for loop
#User needs to input the number
OUTPUT:
7|Page
2020 - 21
PROGRAM: 4
choice='y'
total=0.0
while choice == 'y' or choice == 'y':
item_price=int(input("Enter the price of an item:"))
gst=int(input("Enter the GST% on the item:"))
total=total+(item_price+(item_price*gst)/100)
choice=input("Press y to continue or press 'n' to display total amount:")
print("Total amount to be paid: " ,total)
OUTPUT:
8|Page
2020 - 21
PROGRAM: 5
a=("Hello")
b=("Python") # concatenation
print('The concatenation is: ',a+b)
c=("PYTHON")
print ('The repeated string is: ',c*3) # repetition
d=("python")
print('The character "p" in string exists: ','P' in d) # membership
print('The character "H" in string exists: ','H' in d)
e=("hello python")
print('The slice of the string is: ',e[1:3])
print('The slice of the string is: ',e[-4:-1]) # string slicing
print('The slice of the string is: ',e[5:8])
OUTPUT:
9|Page
2020 - 21
PROGRAM: 6
#program to find number of upper case and lower case letters from the given string
#also demonstrates built in string functions
string1="The text is HELLO PYTHON"
print(string1)
uprcase=0
lwrcase=0
i=0
while i<len (string1):
if string1[i].islower()== True:
lwrcase +=1
if string1[i].isupper()== True:
uprcase +=1
i+=1
print("No. of uppercase letters in the string=",uprcase)
print("No. of lowercase letters in the string=",lwrcase)
print('To upper:',string1.upper())
print('To lower:',string1.lower())
str2=":"
print('Joining ":" between every character:', str2.join(string1))
print('Swapping from Upper case to Lower Case:',string1.swapcase())
print('Partitioning a piece of text from the string:',string1.partition('PYTHON'))
print('Stripping characters from the word "PYTHON":',string1.rstrip("HON"))
print('Comparing whether the string is lower:',string1.islower())
print('Comparing whether the string is Upper:',string1.isupper())
print('Comparing whether the string is space:',string1.isspace())
print('Comparing whether the string is alphabetic:',string1.isalpha())
OUTPUT:
The text is HELLO PYTHON
No. of uppercase letters in the string= 12
No. of lowercase letters in the string= 8
To upper: THE TEXT IS HELLO PYTHON
To lower: the text is hello python
Joining ":" between every character: T:h:e: :t:e:x:t: :i:s: :H:E:L:L:O: :P:Y:T:H:O:N
Swapping from Upper case to Lower Case: tHE TEXT IS hello python
Partitioning a piece of text from the string: ('The text is HELLO ', 'PYTHON', '')
Stripping characters from the word "PYTHON": The text is HELLO PYT
Comparing whether the string is lower: False
Comparing whether the string is Upper: False
10 | P a g e
2020 - 21
PROGRAM: 7
#program to create a list
#performs slicing along with built in function.
list1=[]
n=int(input("Enter the number of element of the list : "))
i=0
while i<n:
x=int(input("Enter the element of the list : "))
list1.append(x)
i=i+1
print('The list elements are:',list1)
print('The list Slicing is:',list1[2:5])
print('The length of the list is:',len(list1))
print('The Maximum Value from the list is:',max(list1))
print('The Maximum Value from the list is:', min(list1))
print('The total sum of the values of the list is:',sum(list1))
OUTPUT:
11 | P a g e
2020 - 21
PROGRAM: 8
tup=(1,2,3,4,5,6)
t=(7,8,9,)
OUTPUT:
12 | P a g e
2020 - 21
PROGRAM: 9
number=[1,2,3,4,5,6,7,8,9,10]
squarednumber=()
print ('The squared numbers are:\n')
for number in number:
squarednumber=(number**2)
print('The square of ',number,' is ',squarednumber)
OUTPUT:
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100
13 | P a g e
2020 - 21
PROGRAM: 10
#Program to find the area and circumference of the circle
#Program to find the area and perimeter of the rectangle
#use of functions for circle and rectangle operation
Circle
import math
defar_circle(r):
returnmath.pi*r*r
defcir_circle(r):
return 2*math.pi*r
Rectangle
defar_rect(l,b):
return l*b
defper_rect(l,b):
return 2*(l+b)
Main Program
import circle
import rectangle
import math
defmainmenu():
print('Menu')
print('1. Area of circle')
print('2. Area of Rectangle')
print('3. Circumference of Circle')
print('4. Perimeter of Circle')
print('5. Quit')
while True:
choice=int(input("Enter your Choice:"))
if(choice==1):
r=float(input("Enter the radius:"))
print ('The area of the Circle is:',circle.ar_circle(r))
print('\n')
mainmenu()
elif(choice==2):
l=float(input("Enter the length:"))
b=float(input("Enter the width:"))
print ('The area of the Rectangle is:',rectangle.ar_rect(l,b))
print('\n')
mainmenu()
elif(choice==3):
14 | P a g e
2020 - 21
mainmenu()
OUTPUT:
Menu
1. Area of circle
2. Area of Rectangle
3. Circumference of Circle
4. Perimeter of Circle
5. Quit
Enter your Choice:1
Enter the radius:5
The area of the Circle is: 78.53981633974483
15 | P a g e
2020 - 21
PROGRAM: 11
defrecurfactorial(n):
if n==1:
return n
else:
return n*recurfactorial(n-1)
num = int(input("Enter a number:"))
if num<0:
print ("The factorail of negative number cannot exist")
elif num==0:
print("The factorial of 0 is 1")
else:
print('The factorial of',num,'is',recurfactorial(num))
OUTPUT:
Enter a number:5
The factorial of 5 is 120
16 | P a g e
2020 - 21
PROGRAM: 12 (1)
# Program to read the text file
#program to implement text file operators.
f=open("test.txt",'r+')
print ("The file that is read is:")
print (f)
print ("File name: ",f.name)
print ("File Mode: ",f.mode)
print ("The file is closed: ",f.closed)
print ("\n")
g=open("test.txt",'r')
print ("The data(only two characters)that is in the file are: ")
data=g.read(2)
print(data)
print ("\n")
h=open("test.txt",'r')
print ("The data that is in the 1st line is: ")
data=h.readline()
print(data)
print ("\n")
i=open("test.txt",'r')
print ("The all data: ")
data=i.readlines()
for line in data:
print(line)
f.close()
print ("The file is closed: ",f.closed)
OUTPUT:
17 | P a g e
2020 - 21
Hi Hello!!!
How r you this morning?
How's Life?
The file is closed: True
PROGRAM: 12 (2)
# Program to write the text file
#program to implement write and append file operators.
f=open("test1.txt",'w')
x=100
f.write("It is the text that is written to the test.txt file.")
f.write("\nThe character size is:")
f.write(str(x))
print ("Text is added to the file successfully!!!!")
g=open("test1.txt",'a')
g.write("\n\nIt is the data that is appended to the text file.")
print ("The data is appended")
g.close()
with open("test1.txt",'a') as h:
h.write("\n\nIt is the data that is appended to the text file using with statement.")
print ("The data is appended using with statement")
g.close()
OUTPUT:
18 | P a g e
2020 - 21
PROGRAM: 13
import pickle
defbndump():
list=[10,20,30,40,50]
f=open('test2.dat','wb')
pickle.dump(list,f)
print("Data added to the binary file")
f.close()
bndump()
defbnload():
g=open('test2.dat','rb')
data=pickle.load(g)
print("\n")
print("The data in the binary file is")
print(data)
g.close()
bnload()
OUTPUT:
19 | P a g e
2020 - 21
PROGRAM: 14
# Program to copy the content from a file and write on the other.
importos
deffilecopy(file1,file2):
f1=open(file1,'r')
f2=open(file2,'w')
for line in f1:
f2.write(line)
f1.close()
f2.close()
def main():
filename1=input('enter the source file name:')
filename2=input('enter the destination file name:')
filecopy(filename1,filename2)
main()
OUTPUT:
20 | P a g e
2020 - 21
PROGRAM: 15
defcapitalize_sentence():
f1=open('test_reports.txt','r')
f2=open('file1.txt','w')
while 1:
line=f1.readline() #read a line
if not line:
break # encounter eof
#strip of the new line character and any white space on the right
line=line.rstrip()
linelength=len(line)
str='' #string to concatenate all characters from line
str=str+line[0].upper()
i=1
#loop to check a line to connect uppercase
while i <linelength:
str=str+line[i]
i=i+1
if i>=linelength:
break
str=str+line[i]
i=i+1
f2.write(str)
print ('Conversion done')
else:
print('source file does not exist')
f1.close()
f2.close()
capitalize_sentence()
OUTPUT:
21 | P a g e
2020 - 21
Conversion done
Conversion done
PROGRAM: 16
import time
def sum_n_2(n):
start = time.time() #starting time
sum=0
for i in range (1,n+1):
sum = sum+1
end = time.time() #Ending time
t=end-start #actual time taken
print ('The sum is ',sum,' and time taken is :',t,'seconds')
sum_n_2(100000)
import time
start=time.time()
def sum_n_2(n):
return(n+(n+1))/2
end=time.time()
t=end-start
print('The sum is ',(sum_n_2(100000)),' and the time taken is:',t,'seconds')
22 | P a g e
2020 - 21
OUTPUT:
The sum is 100000 and time taken is : 0.0 seconds
The sum is 100000.5 and the time taken is: 0.0 seconds
PROGRAM: 17
#program to add, delete and display the records of an Employee using list
#implementation of stack
Employee=[ ]
c="y"
while (c=="y"):
print ("1. Push")
print("2. Pop")
print("3. Display")
choice= int(input("Enter your choice: "))
if (choice==1):
e_id=input("Enter Employee no.:")
ename=input ("Enter the Employee name :")
emp=(e_id, ename)
Employee.append(emp)
elif (choice==2):
if (Employee==[ ]):
print ("Stack empty")
else:
e_id, ename=Employee.pop()
print("Deleted element is:",e_id, ename)
elif (choice==3):
i=len(Employee)
while i> 0:
print(Employee[i-1])
i=i-1
else:
print("Wrong Input")
c= input("Do you want to continue or not?")
23 | P a g e
2020 - 21
OUTPUT:
1. Push
2. Pop
3. Display
Enter your choice: 1
Enter Employee no.:101
Enter the Employee name :AAAA
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 1
Enter Employee no.:102
Enter the Employee name :BBBB
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 3
('102', 'BBBB')
('101', 'AAAA')
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 2
Deleted element is: 102 BBBB
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 3
('101', 'AAAA')
Do you want to continue or not?n
24 | P a g e
2020 - 21
PROGRAM: 18
#program to add, delete and display the records of an Employee using list
#implementation of Queue
Library=[ ]
c="y"
while (c=="y"):
print ("1.Insert")
print("2. Delete")
print("3. Display")
choice= int(input("Enter your choice: "))
if (choice==1):
book_id=input("Enter book_id.:")
bname=input("Enter the book name:")
lib=(book_id,bname)
Library.append(lib)
elif (choice==2):
if (Library==[ ]):
print ("Queue empty")
else:
print("Deleted element is:",Library.pop(0))
elif (choice==3):
i=len(Library)
for i in range (0, i):
print(Library[i])
else:
print("Wrong Input")
c= input("Do you want to continue or not?")
25 | P a g e
2020 - 21
OUTPUT:
1.Insert
2. Delete
3. Display
Enter your choice: 1
Enter book_id.:101
Enter the book name:AAAA
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 1
Enter book_id.:102
Enter the book name:BBBB
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 3
('101', 'AAAA')
('102', 'BBBB')
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 2
Deleted element is: ('101', 'AAAA')
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 3
('102', 'BBBB')
Do you want to contunue or not?n
26 | P a g e
2020 - 21
PROGRAM: 19
OUTPUT:
Enter number of sides: 8
Enter the length of the sides: 3
The area of the polygon is: 43.45584412271571
27 | P a g e
2020 - 21
PROGRAM: 20
r=b**2-4*a*c
if r>0:
num_roots=2
x1=(((-b)+sqrt(r))/(2*a))
x2=(((-b)-sqrt(r))/(2*a))
print("The two roots are: ",x1, "and",x2)
elif r==0:
num_roots=1
x=(-b)/2*a
print("There is on root:",x)
else:
num_roots=0
print("noroots,discriminant<0")
28 | P a g e
2020 - 21
OUTPUT:
The quadratic equation is: (a*x**2)+b*x+c
a: 2
b: 3
c: 1
The two roots are: -0.5 and -1.0
PROGRAM: 21
import math
arclength()
29 | P a g e
2020 - 21
OUTPUT:
The diameter of circle:50
Angle measure:90
The arclength is: 39.269908169872416
PROGRAM: 22
for i in range(len(b_num)):
digit=b_num.pop()
if digit=="1":
value=value+math.pow(2,i)
print("The decimal value of the number is:",value)
OUTPUT:
Enter binary number:1100
The decimal value of the number is: 12.0
30 | P a g e
2020 - 21
PROGRAM: 23
#python program that takes a list of words and return the length of the longest
def find_longest_word(words_list):
word_len=[]
for n in words_list:
word_len.append((len(n),n))
word_len.sort()
returnword_len[-1][1]
print(find_longest_word(['JSP','Computer','Python3']))
OUTPUT:
31 | P a g e
2020 - 21
Computer
PROGRAM: 24
defcapitalize_first_last_letter(str1):
str1=result=str1.title()
result= ""
for word in str1.split():
result+=word[:-1]+word[-1].upper()+ " "
return result[:-1]
32 | P a g e
2020 - 21
OUTPUT:
PythoNStrinGLibrarYFunctionS
ImplementatioN
PROGRAM: 25
defswap_case_string(str1):
result_str=""
for item in str1:
ifitem.isupper():
result_str+=item.lower()
else:
result_str+=item.upper()
returnresult_str
print(swap_case_string("String Module in"))
print(swap_case_string("Python"))
print(swap_case_string("Matplotlib Library"))
33 | P a g e
2020 - 21
OUTPUT:
sTRINGmODULE IN
pYTHON
mATPLOTLIBlIBRARY
PROGRAM: 26
OUTPUT:
How are you
34 | P a g e
2020 - 21
PROGRAM: 27
filename="testfile.txt"
filehandle=open(filename,'r')
filedata=filehandle.read()
print(filedata)
OUTPUT:
Hello World
35 | P a g e
2020 - 21
Hello Ppython
Good Morning
How are you
PROGRAM: 28
#program for inserting a record in a binary file-student.dat
import pickle
record=[]
while True:
roll_no=int(input("Enter student roll no:"))
name=input("Enter student name:")
marks=int(input("Enter student marks:"))
data=[roll_no,name,marks]
record.append(data)
choice=input("Wish to enter more records(Y/N)?:")
ifchoice.upper() == "N":
break
f=open("D:/student","wb")
pickle.dump(record,f)
print("record added")
f.close()
OUTPUT:
36 | P a g e
2020 - 21
PROGRAM: 29
import pickle
f=open("D:/student",'rb')
stud_rec=pickle.load(f) #to read the object from the opened file
print("Contents of the student file are")
#reading hte field from file
for R in stud_rec:
roll_no=R[0]
name=R[1]
marks=R[2]
print(roll_no,name,marks)
f.close()
37 | P a g e
2020 - 21
OUTPUT:
Contents of the student file are
101 AAAA 98
102 BBBB 75
PROGRAM: 30
#program to read record from a file "student.dat" using search method by roll no
import pickle
f=open("D:/student",'rb')
stud_rec=pickle.load(f) #to read the object from the opened file
found=0
rno=int(input("Enter rollno to search:"))
for R in stud_rec:
roll_no=R[0]
print("Successful search",R[1],"found !")
found=1
break
if found==0:
print("sorry,record not found")
38 | P a g e
2020 - 21
f.close()
OUTPUT:
Enter rollno to search:101
Successful search AAAA found !
PROGRAM: 31
Import os
import pickle
f=open("student.dat","ab")
pickle.dump(rec,f)
f.close()
defupdateMarks(r,m):
f=open("student.dat","rb")
reclst=[]
while True:
try:
rec=pickle.load(f)
reclst.append(rec)
exceptEOFError:
break
f.close()
for i in range(len(reclst)):
ifreclst[i]['Rollno']==r:
reclst[i]['Marks']=m
f=open("student.dat","wb")
for x in reclst:
pickle.dump(x,f)
f.close()
41 | P a g e
2020 - 21
while True:
print("1: Insert rec")
print("2: Display rec")
print("3: Search rec")
print("4: Update rec")
print("5: Delete rec")
print("Enter your choice 0 to exit")
choice=int(input("Enter your choice:"))
if choice == 0:
break
elif choice == 1:
insertRec()
elif choice == 2:
readRec()
elif choice == 3:
r=int(input("Enter a rollno to search:"))
searchRollNo(r)
elif choice == 4:
r=int(input("Enter a rollno:"))
m=int(input("Enter new marks:"))
updateMarks(r,m)
elif choice == 5:
r=int(input("Enter the rollno:"))
deleteRec(r)
OUTPUT:
1: Insert rec
2: Display rec
3: Search rec
4: Update rec
5: Delete rec
Enter your choice 0 to exit
Enter your choice:1
enter the roll num:101
enter the name:AAA
enter the marks:98
42 | P a g e
2020 - 21
PROGRAM: 32
import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f)#csv_reader is the reader obeject
columns = next(csv_reader)
c=0;
#Reading the student file record by record
for row in csv_reader :
c=c+1
print("No.of record are:",c)
43 | P a g e
2020 - 21
OUTPUT:
No.of record are: 5
PROGRAM: 33
import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f) #csv_reader is the reader obeject
for row in csv_reader:
print(','.join(row))
f.close()
44 | P a g e
2020 - 21
OUTPUT:
Roll,name,Class
101,AA,10
102,BB,9
103,CC,10
104,DD,11
105,EE,12
PROGRAM: 34
import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f) #csv_reader is the reader obeject
name=input("Enter the name to be searched:")
for row in csv_reader:
if(row[0]==name):
print(row)
45 | P a g e
2020 - 21
OUTPUT:
PROGRAM: 35
import csv
#Field names
fields =['Name', 'class', 'Year', 'Percent']
#data row of csv file
rows = [
['Rohit', 'XII','2003','92'],
['Shaurya','XI','2004','52'],
46 | P a g e
2020 - 21
OUTPUT:
File created
PROGRAM: 36
import csv
#Field names
fields =['Name', 'class', 'Year', 'Percent']
#data row of cav file
rows = [
['Rohit', 'XII','2003','92'],
47 | P a g e
2020 - 21
['Shaurya','XI','2004','52'],
['Deep', 'XII', '2002','85'],
['Prerna', 'XI, 2006','35'],
['Lakshya', 'XII', '2005','72']
]
#name of csv file
OUTPUT:
PROGRAM: 37
Output:
<mysql.connector.connection.MySQLConnection object at 0x02DAFBF0>
48 | P a g e
2020 - 21
Output:
('information_schema',)
('computer',)
('demodatabase',)
('mysql',)
#to create a table and show the description using python-mysql connectivity.
importmysql.connector
mydb=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database="demodatabase")
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE student(rollnoint(3) Primary key,snamevarchar(15),age
int(3),city char(8))")
mycursor.execute("DESC student")
for x in mycursor:
print(x)
Output:
('rollno', 'int(3)', 'NO', 'PRI', '', '')
('sname', 'varchar(15)', 'YES', '', None, '')
('age', 'int(3)', 'YES', '', None, '')
('city', 'char(8)', 'YES', '', None, '')
PROGRAM: 38
# Program to demonstrate four major operations
#performed on a table through MY-SQL connectivity
def menu():
c='y'
while (c =='y'):
print ('1. add record')
print('2. update record')
49 | P a g e
2020 - 21
defadddata():
importmysql.connector
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database="computer")
mycursor =db.cursor()
mycursor.execute("INSERT INTO student VALUES('Ritu',4000,'science',354,'B',11)")
mycursor.execute("INSERT INTO student VALUES('Akush',6000,'commerce',256,'A',12)")
mycursor.execute("INSERT INTO student VALUES('Pihu',3566,'Humanities',458,'C',11)")
mycursor.execute("INSERT INTO student VALUES('Tinku',8900,'science',457,'A',12)")
db.commit()
print("Records added")
50 | P a g e
2020 - 21
defupdatedata():
importmysql.connector
try:
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database='computer')
mycursor =db.cursor()
sql=("update student set stipend=5000 where name='Ritu'")
mycursor.execute(sql)
print ("Record Updated")
db.commit()
except Exception as e:
print (e)
defdeldata():
importmysql.connector
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database='computer')
mycursor =db.cursor()
sql=("delete FROM student where name='Ritu'")
mycursor.execute(sql)
print ("Record Deleted")
db.commit( )
menu()
OUTPUT:
5. Exiting
Enter your choice:1
Records added
52 | P a g e