0 - Class-Xii Practical 2019-20-Latest
0 - Class-Xii Practical 2019-20-Latest
0 - Class-Xii Practical 2019-20-Latest
CLASS-XII
COMPUTER SCIENCE (083)
PRACTICAL FILE
SUBMITTED BY:
Roll No:……………….
Name:
Date:………………….
Page | 2
2. Write a program to input a character and to print whether a
given character is an alphabet, digit or any other character.
ch=input("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")
Page | 3
3. Write a program for binary search.
def Bsearch(ar,item):
beg=0
last=len(ar)-1
while(beg<=last):
mid=(beg+last)//2
if(item==ar[mid]):
return mid
elif(item>ar[mid]):
beg=mid+1
else:
last=mid-1
else:
return False
N=int(input("Enter total numbers of the list"))
print("\nEnter elements for the list\n")
ar=[0]*N #initialize list of size N with zero
for i in range(N):
ar[i]=int(input("Element"+str(i)+":"))
item=int(input("Enter element to be searched"))
index=Bsearch(ar,item)
if index:
print("Element found at", index+1)
else:
print("Element not found")
Page | 4
4. Write a program to count the number of vowels present in a text file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for f1 in f.read():
if f1=='a'or f1=='e'or f1=='i'or f1=='o‘ or f1=='u':
count=count+1
print(count)
f.close()
Page | 5
5. Write a program to write those lines which have the character 'p' from one text
file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines()
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
6. Write a program to count number of words in a file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for word in f.read().split():
count=count+1
print(count)
f.close()
Page | 6
7. Write a program to insert n records in a binary file student.dat.
import pickle
ch='y'
f = open('d:/student.dat','wb')
while ch=='y':
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks'))
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
pickle.dump(rec,f)
ch=input("more entry?")
f.close()
Page | 7
8. Write a program to read records from binary file student.dat.
import pickle
f = open('d:/student.dat','rb')
while True:
try:
rec = pickle.load(f)
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
except EOFError:
break
f.close()
Page | 8
9. Write a program to implement search operation in a binary file.
import pickle
f = open('d:/student.dat','rb')
flag = False
r=int(input("Enter rollno to be searched"))
while True:
try:
rec = pickle.load(f)
if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()
Page | 9
10.Write a program to update a record stored in binary file student.dat.
import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be updated"))
m=int(input("enter correct marks"))
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
for i in range (len(reclst)):
if reclst[i]['Rollno']==r:
reclst[i]['Marks'] = m
f = open('d:/student.dat','wb')
for x in reclst:
pickle.dump(x,f)
f.close()
Page | 10
11.Write a program to delete a record from binary file.
import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be deleted"))
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f = open('d:/student.dat','wb')
for x in reclst:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()
Page | 11
12.Write a program to create a CSV file and read it.
import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP Name""%10s"%"Salary")
print("---------------------------------------------")
for row in myreader:
if len(row)!=0:
print("%10s"%row[0],"%15s"%row[1],"%10s"%row[2])
Note:
1.Create a notepad file myfile.csv in d:\. Write data for
file with comma separated.
2.Go to Tools->Folder Option->view->uncheck hide
extension for unknown file types
3.Rename myfile.csv.txt -> myfiel.csv
Page | 12
13. Write a program to count umber of records from CSV file.
import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
count=0
print("%10s"%"EMPNO","%20s"%"EMP
Name""%10s"%"Salary")
print("--------------------------------------------")
for row in myreader:
if len(row)!=0:
print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])
count=count+1
print("--------------------------------------------")
print("%30s"% "Total Records are:", count)
print("--------------------------------------------")
Page | 13
14.Write a python function sin(x,n) to calculate the value of sin(x) using its Taylor
series expansion up to n terms.
import math
def fact(k):
if k<=1:
return 1
else:
return k*fact(k-1)
Page | 15
i=0
while i<len(ar) and ar[i]!=item:
i=i+1
if i<len(ar):
return i
else:
return Flase
N=int(input("Enter total numbers of the list"))
print("\nEnter elements for the list\n")
ar=[0]*N #initialize list of size N with zero
for i in range(N):
ar[i]=int(input("Element"+str(i)+":"))
item=int(input("Enter element to be searched"))
index=Lsearch(ar,item)
if index:
print("Element found at", index+1)
else:
print("Element not found")
Page | 16
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1
for i in range(size-1):
if(ar[i]<=item and item<ar[i+1]):
pos=i+1
break
if(pos==-1 and i<=size):
pos=size
return pos
def shift(ar,pos):
ar.append(None) # add an empty element at the end
size=len(ar)
i=size-1
while i>=pos:
ar[i]=ar[i-1]
i=i-1
list=[10,20,30,40,50,60,70]
print("list in sorted order is")
print(list)
item=int(input("Enter element to be inserted:"))
position=findpos(list,item)
shift(list,position)
list[position]=item
print("The list after insertion is:",item,"is")
print(list)
18.Write a menu based program to perform PUSH, POP and DISPLAY operation on
stack in python.
Page | 17
s=[]
def push(a):
s.append(a)
def pop():
if(s==[]):
print("Stack Empty")
else:
print("Element Deleted is :",s.pop())
def display():
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
c="y"
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
choice=int(input("Enter your choice"))
if(choice==1):
a=input("Enter any number: ")
push(a)
elif (choice==2):
pop()
elif(choice==3):
display()
else:
print("Wrong Input")
c=input("Do you want to continue?")
Page | 18
Page | 19
19.Write a program to connect Python with MySQL using database connectivity and
perform the following operations on data in database: Fetch, Update and delete
the data.
import mysql.connector
import datetime
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="Class_management")
mycursor=mydb.cursor()
def testadd():
L=[]
Rno=int(input("Enter Roll no:-"))
L.append(Rno)
Sname=input("Enter Student's name:-")
L.append(Sname)
Class=int(input("Enter Class:-"))
L.append(Class)
Dob=input("Enter DOB:-")
L.append(Dob)
Fees=float(input("Enter Fees :-"))
L.append(Fees)
Address=input("Enter Student's Address:-")
L.append(Address)
Phone_no=int(input("Enter Phone no:-"))
L.append(Phone_no)
Fname=input("Enter Father's name:-")
L.append(Fname)
Mname=input("Enter Mother's name:-")
L.append(Mname)
Sub=input("Enter Student's Subjects:-")
L.append(Sub)
value=L
value=(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)
sql="insert into
class_info(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)values(%s,
%s,%s,%s,%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,value)
mydb.commit()
def testsearch():
rn=int(input("Enter Roll no. to search:-"))
rl=(rn,)
sql="select * from class_info where Rno=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("Details are as follows:")
print("(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)")
for x in res:
Page | 20
print(x)
def testdelete():
r=int(input("Enter the Roll no. to delete:-"))
rl=(r,)
sql="delete from class_info where Rno=%s"
mycursor.execute(sql,rl)
mydb.commit()
def testupdate():
rr=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(rr,)
value=int(input("Enter the Roll no to update:-"))
rll=(value,)
Page | 21
value1()
elif(userinput==3):
value2()
elif(userinput==4):
value3()
else:
print("Wrong Choice")
#now=datetime.datetime.now()
#trID="S"+str(now.year)+str(now.month)+str(now.day)+str(now.hour)
+str(now.minute)+str(now.second)
#print("Reference ID is",trID)
def menu():
print("************************************** ")
print("* Press 1- To Add Entry * ")
print("* Press 2- To Search record * ")
print("* Press 3- To Delete record * ")
print("* Press 4- To Update record * ")
print("************************************** ")
userinput=int(input("Please select an option from above"))
if(userinput==1):
testadd()
elif(userinput==2):
testsearch()
elif(userinput==3):
testdelete()
elif(userinput==4):
testupdate()
else:
print("Wrong Choice")
def runagain():
again=input("\Want to run again y/n?")
while(again=='y'):
menu()
again=input("\nWant to run again y/n?")
menu()
runagain()
print("Thanks for using Program")
Page | 22
Page | 23
20.Create the following table PRODUCT in MySql and answer the questions follows:
TABLE : PRODUCT
Page | 24
ii. To display average price of product sorted on the basis of Manufacturer.
select Manufacturer, avg(price) from PRODUCT group by Manufacturer;
Page | 25
v. To display product name and price of product having P_ID either BS01 or
FW12.
select ProductName,Price from product where P_ID in('BS01','FW12');
Page | 26
viii. To print average Price of product from manufacturer either ‘ABC’ or ‘XYZ’.
select avg(price) from PRODUCT where Manufacturer in (‘ABC’,’XYZ’);
Page | 27
xiii. To print manufacturer wise price when total price is greater than 100;
Select manufacturer, sum(price) from PRODUCT group by Manufacturer
having sum(price)>100;
*************************************************
Page | 28