List of Practical Programs CLASS XII 2022-23 CODE:083 Computer Science Python Programs
List of Practical Programs CLASS XII 2022-23 CODE:083 Computer Science Python Programs
Python Programs
• Perimeter of a rectangle(2*length*breadth)
• Circumference of a circle(2*3.14*r)
• Sum of digits
• Reverse a string
• Selection sort
• Bubble sort
6. Write a menu driven program in Python using function to read a text file and
• Read a text file line by line and display each word separated by a #.
• Read a text file and remove all the lines that contain the character `a’ in a file and
write it to another file.
8. Write a program in Python using function to read a text file and display the number of
vowels/ consonants/ uppercase/ lowercase characters/special characters in the file.
9. Write a menu driven program in Python using function to read a text file and
• Append the words starting with letter ‘T’ or ‘t’ in a given file in python.
• count the particular word occurrences in given string, number of times in python.
10. Write a menu driven program in Python to perform linear and binary search on a
set of numbers.
11. Write a menu driven program in Python using Pickle library and
◦ Admission number
◦ Student name
◦ Age
12. Write a program in python using Pickle library having a binary file “Book.dat” has
structure {BookNo, Book_Name, Author, Price}.
i. Write a user defined function CreateFile() to input data for a record and add to
“Book.dat” .
ii. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in the
binary file “Book.dat”
13. Write a menu driven program in Python using Pickle library and
◦ Travelid
◦ From
◦ To
14. Write a menu driven program in Python to create a CSV file with following data
• Roll no
• Name of student
• Mark in Sub1
• Mark in sub2
• Mark in sub3
• Mark in sub4
• Mark in sub5
15. Write a program in Python to create a CSV file by entering user-id and
password, read and search the password for given userid.
Solution for Program1:
import math
def prect():
l=float(input("Enter the length of rectangle : "))
b=float(input("Enter the breadth of rectangle : "))
a = 2*l*b
print("The Perimeter of a rectangele :",a)
def ccircle():
r = float(input("Enter the radius of circle :"))
a = 2*math.pi * r
print("The circumference of circle %0.2f" %a)
prect()
ccircle()
def sumn(n):
if n < 0:
print("Enter a positive number")
else:
sum = 0
for i in range(1,n+1):
sum += i
print("The sum of natural numbers upto ",n," is ",sum)
def sumd(n):
sum=0
while(n>0):
rem=n%10
sum=sum+rem
n=n//10
print("The sum of digits is :",sum)
def fact(n):
factorial=1
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
def fibo(n):
print("The Fibonacci Series is:")
f1 = 0
f2 = 1
print(f1)
print(f2)
if n < 0:
print("Incorrect input entered")
else:
for i in range(2,n):
f3 = f1 + f2
f1 = f2
f2 = f3
print(f2)
while(1):
print('''menu
1. factorial
2. Fibonacci Series
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
n=int(input("Enter the n value to calculate Factorial"))
fact(n)
elif (ch==2):
n=int(input("Enter the n value to calculate Fibonacci"))
fibo(n)
elif (ch==3):
break
Solution for Program4:
def palindrome(s):
for i in range(0, int(len(s)/2)):
if s[i] != s[len(s)-i-1]:
print("The string is not a palindrome")
break
else:
print("The string is a palindrome")
def lens(s):
count=0
for i in s:
count=count+1
print("The length of the string is",count)
def revs(s):
print("The reverse of the string is ")
for i in range(0,len(s)):
a=s[len(s)-i-1]
print(a,end="")
while(1):
print('''\nmenu
1. Palindrome
2. Length of string
3. Reverse a string
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
s = input("Enter the string")
palindrome(s)
elif (ch==2):
s = input("Enter the string")
lens(s)
elif (ch==3):
s = input("Enter the string")
revs(s)
elif (ch==4):
break
else:
print('invalid input')
Solution for Program5:
def selection():
list=[]
n=int(input("Enter a value for n"))
for i in range(n):
l=int(input("Enter a value for list:"))
list.append(l)
print(list)
for i in range(0,len(list)):
for j in range(i+1,len(list)-1):
if list[i]>list[j]:
temp=list[i]
list[i]=list[j]
list[j]=temp
print("The numbers after sorting")
print(list)
def bubble():
list=[]
n=int(input("Enter a value for n"))
for i in range(n):
l=int(input("Enter a value for list:"))
list.append(l)
print(list)
for i in range(0,len(list)):
for j in range(0,len(list)-i-1):
if list[j]>list[j+1]:
temp=list[j]
list[j]=list[j+1]
list[j+1]=temp
while(1):
print('''menu
1. Selection Sort
2. Bubble Sort
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
selection()
elif ch==2:
bubble()
else:
break
Solution for Program6:
def cword():
fin=open(r"d:\python\book1.txt",'r')
str=fin.read()
L=str.split()
print(L)
cwords=0
for i in L:
cwords=cwords+1
print("\nTotal words in text file:",cwords)
fin.close( )
def cchars():
fin=open(r"d:\python\book1.txt",'r')
str1=fin.read()
cchar=0
for i in str1:
cchar=cchar+1
print("\nTotal words in text file:",cchar)
fin.close( )
while(1):
print('''menu
1. Count Word
2. Count Characters
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
cword()
elif ch==2:
cchars()
else:
break
Solution for Program7:
def fun1():
fp=open("poem.txt","r")
s=fp.readlines()
l=len(s)
fp.seek(0)
for i in range(l):
r=fp.readline()
sp=r.split()
for j in sp:
print(j,end="#")
def remov():
f=open("poem.txt",'r')
o=[]
for i in f:
#print(i)
if not "a" in i:
o.append(i)
for i in o:
print(i)
f.close()
f1=open("output.txt","w")
f1.writelines(o)
f.close()
while(1):
print('''menu
1. Word with #
2. Remove
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
fun1()
elif ch==2:
remov()
else:
break
Solution for Program8:
fin=open("poem.txt",'r')
str=fin.read()
count=0
cos=0
up=0
lo=0
sp=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
else:
cos=cos+1
for i in str:
if i.isupper():
up=up+1
elif i.islower():
lo=lo+1
else:
sp=sp+1
fin.close()
Solution for Program9:
def startsT():
f=open(r"C:\Users\91984\Desktop\poem.txt",'r')
li=[]
s=f.read()
r=s.split()
#print(r)
for i in r:
l=len(i)
if i.startswith("T",0,l):
li.append(i)
if i.startswith("t",0,l):
li.append(i)
print(li)
def cwords():
fin=open(r"C:\Users\91984\Desktop\poem.txt",'r')
str=fin.read()
L=str.split()
count=0
found=0
s=input("Enter a word to search")
for i in L:
if i==s:
count=count+1
found=1
if found==1:
print("Matched words",count)
else:
print("No match found")
fin.close( )
while(1):
print('''menu
1. To check words starts with T or t
2. To Count particular word occurrence
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
startsT()
elif ch==2:
cwords()
else:
break
Solution for Program10:
def binarysearch(arr,key):
low=0
high=len(arr)-1
found=0
while low<=high:
mid=(low+high)//2
if arr[mid]==key:
found=1
break
else:
if key<arr[mid]:
high=mid-1
else:
low=mid+1
if found==1:
print("The element is present in position",mid+1)
else:
print("The element is not present in the list")
def lsearch(arr,key):
for i in range(0,len(arr)):
if key==arr[i]:
found=0
break
if found==0:
print("The element is present in position",i+1)
else:
print("The element is not present in the list")
while(1):
print('''menu
1. Linear Search
2. Binary Search
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
lst=[]
l=int(input("Enter n value:"))
for i in range(l):
s=int(input("Enter elements to list"))
lst.append(s)
print(lst)
ele = int(input("Enter the element to search"))
res = lsearch(lst,ele)
elif (ch==2):
lst=[]
l=int(input("Enter n value:"))
for i in range(l):
s=int(input("Enter elements to list"))
lst.append(s)
lst.sort()
print(lst)
key=int(input("Enter a key value"))
binarysearch(lst,key)
elif (ch==3):
break
else:
print('invalid input')
import pickle
def writefile(file):
admno = int(input("Enter the admission number :"))
name = input("Enter the name of student :")
age = int(input("Enter the age of student "))
data = admno,name,age
pickle.dump(data,file)
def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
return
def above(file):
cutoff = int(input("Enter the cut off age :"))
while(1):
try:
data = pickle.load(file)
if(data[2]>=cutoff):
print(data)
except EOFError :
return
def search(file):
admno = int(input("Enter the admission number :"))
flag = 0
while(1):
try:
data = pickle.load(file)
if(data[0]==admno):
print(data)
flag = 1
return flag
except EOFError :
return flag
file = open("student.dat","ab+")
while(1):
print('''menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file.seek(0,0)
writefile(file)
elif (ch==2):
file.seek(0,0)
readfile(file)
elif (ch==3):
file.seek(0,0)
above(file)
elif (ch==4):
file.seek(0,0)
res = search(file)
if(res == 0):
print("Record not found")
elif (ch==5):
break
else:
print('invalid input')
Solution for Program12:
import pickle
def createfile():
fp=open("book","ab+")
bookno=input("Enter Book number")
bookname=input("Enter Book name")
author=input("Enter author")
price=input("Enter Price")
data={'BNo':bookno,'BName':bookname,'BAuthor':author,'BPrice':price}
pickle.dump(data,fp)
def display():
fp=open("book","rb")
try:
while True:
s=pickle.load(fp)
print("Book ID:",s['BNo'])
print("Book Name:",s['BName'])
print("Author:",s['BAuthor'])
print("Price:",s['BPrice'])
print()
except EOFError:
fp.close()
def countrec(user):
fp=open("book","rb")
c=0
try:
while True:
s=pickle.load(fp)
if user==s['BAuthor']:
c=c+1
except EOFError:
return c
while(1):
print("1.create a file")
print("2. Countrec")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice"))
if ch==1:
createfile()
elif ch==2:
user=input("Enter Author name")
rec=countrec(user)
print("Total books by",user,"is",rec)
elif ch==3:
display()
elif ch==4:
break
import os
import pickle
def updateStock(trid):
e=open('travel.dat','rb+')
found=0
try:
while True:
rpos=e.tell()
s=pickle.load(e)
if s['Tid']==trid:
froms = input("Enter the new starting point :")
to = input("Enter the new destination ")
s['From']=froms
s['To']=to
e.seek(rpos)
print(s)
pickle.dump(s,e)
found=1
except EOFError:
if found==0:
print("sorry, no matching record found")
else:
print("Record(s) Successfully Updated")
def deleteRec(trid):
f = open('travel.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f = open('travel.dat','wb')
for x in reclst:
if x['Tid']==trid:
continue
pickle.dump(x,f)
f.close()
while(1):
print('Type 1 to insert Travel Details.')
print('Type 2 to display Travel Details.')
print('Type 3 to Update Travel Details.')
print('Type 4 to Delete a Record.')
print('Type 5 to exit')
choice = int(input('Enter you choice:'))
if choice == 1:
appenddata()
elif choice == 2:
display()
elif choice == 3:
tid = int(input('Enter a Tid:'))
updateStock(tid)
elif choice == 4:
tid = int(input('Enter a Travel Id:'))
deleteRec(tid)
elif choice == 5:
break
else:
print('invalid input')
import csv
def writefile(file):
l=[]
writer = csv.writer(file)
r = int(input("Enter the roll no :"))
n = input("Enter the name :")
s1 = int(input("Enter the marks for Subject 1 "))
s2 = int(input("Enter the marks for Subject 2 "))
s3 = int(input("Enter the marks for Subject 3 "))
s4 = int(input("Enter the marks for Subject 4 "))
s5 = int(input("Enter the marks for Subject 5 "))
data = [r,n,s1,s2,s3,s4,s5]
writer.writerow(data)
def readfile(file):
reader = csv.reader(file)
for r in reader:
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):
print("Subject ",i-1,"marks :",r[i])
total = 0
for i in range(2,7):
total = total + int(r[i])
print ("Total : ",total)
print("Percentage : ", total/5)
def read90(file):
reader = csv.reader(file)
for r in reader:
flag = 0
for i in range(2,7):
if(int(r[i])>90):
flag = 1
if(flag==1):
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):
print("Subject",i-1,"marks :",r[i])
file = open("travel.csv","a+")
writer = csv.writer(file)
writer.writerow(["Roll No", "Name", "Sub1", "Sub2", "Sub3", "Sub4" , "Sub5"])
file.close()
while(1):
print('''menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file = open("student.csv","a+",newline='')
writefile(file)
file.close()
elif (ch==2):
file = open("student.csv","r")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==3):
file = open("student.csv","r")
file.seek(0,0)
read90(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')
Solution for Program15:
import csv
def writefile(file):
l=[]
writer = csv.writer(file)
r = input("Enter the userid :")
n = input("Enter the password :")
data = [r,n]
writer.writerow(data)
def readfile(file):
reader = csv.reader(file)
for r in reader:
print("User Id: ",r[0])
print("Password :",r[1])
def search(file):
reader = csv.reader(file)
userid=input("Enter user id")
for r in reader:
if (r[0]==userid):
print("User Id: ",r[0])
print("Password :",r[1])
file.close()
while(1):
print('''menu
1. Write to CSV file
2. Display Userid and password
3. Search Userid
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file = open("pass.csv","a+",newline='')
writefile(file)
file.close()
elif (ch==2):
file = open("pass.csv","r")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==3):
file = open("pass.csv","r")
file.seek(0,0)
search(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')