Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views28 pages

0 - Class-Xii Practical 2019-20-Latest

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 28

AISSCE 2020-21

CLASS-XII
COMPUTER SCIENCE (083)
PRACTICAL FILE

KENDRIYA VIDYALAYA ALIGANJ LUCKNOW

SUBMITTED BY:
Roll No:……………….
Name:
Date:………………….

 Signature of Internal Examiner:

 Signature of External Examiner:


1. Write a program in python to check a number whether it is
Prime or not.

num=int(input("Enter the number: "))


for i in range(2,num):
if num%i==0:
print(num, "is not prime
number")
break
else:
print(num,"is prime number")

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)

step=int(input("How many terms : "))


x=int(input("Enter the value of x :"))
sum=0
for i in range(step+1):
sum+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)
print("The result of sin",'(', x, ')', "is :", sum)

15.Write a program to generate random numbers between 1 to 6 and check whether


a user won a lottery or not.
Page | 14
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

16.Write a program to create a function Lsearch to implementr linear search in a list.


def Lsearch(ar,item):

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")

17.Write a program to insert an element at the list.


def findpos(ar,item):

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,)

sql=("update class_info set Rno=Rno+%s where Rno=%s")


data=(value,e)

rf=int(input("Enter the Roll no. to update:-"))


sqll=("select * from class_info where Rno=%s")
rl=(ru,)
value1=int(input("Enter the Fees to update:-"))
rll=(value1,)

sql=("update class_info set Fees=Fees+%s where Fees=%s")


data=(value1,e)
mycursor.execute(sql,data)
mydb.commit()
ra=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(ra,)
value2=input("Enter the Address to update:-")
rll=(value2,)

sql=("update class_info set Address=Address+%s where Address=%s")


data=(value2,e)
rp=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(rp,)
value3=int(input("Enter the Phone_no to update:-"))
rll=(value3,)

sql=("update class_info set Phone_no=Phone_no+%s where Phone_no=%s")


data=(value,e)
def update():
print("************************************** ")
print("* Press 1- To Update Roll no * ")
print("* Press 2- To update Fees * ")
print("* Press 3- To update Address * ")
print("* Press 4- To update Phone_no * ")
print("************************************** ")
userinput=int(input("Please select an option from above"))
if(userinput==1):
value()
elif(userinput==2):

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

P_ID ProductName Manufacture Price


r
TP01 Talcom LAK 40
Powder
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
PP01 Hand Wash NULL 95

i. To increase the Price of all Products by 10.


update PRODUCT set price=price+10;

Page | 24
ii. To display average price of product sorted on the basis of Manufacturer.
select Manufacturer, avg(price) from PRODUCT group by Manufacturer;

iii. To display minimum and maximum Price of product Manufacturer wise.


select manufacturer, min(price), max(price) from PRODUCT group by
Manufacturer;

iv. To display details of product having name ends with ‘h’.


select * from product where ProductName like '%h';

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');

vi. To display manufacturer wise sum of Price in descending order of Price.


select Manufacturer, sum(Price) from PRODUCT group by manufacturer
order by sum(price) desc;

vii. To count and print unique Manufacturer.


Select count(distinct Manufacturer) from PRODUCT;

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’);

ix. To delete record of ‘Shampoo’.


delete from PRODUCT where ProductName=’Shampoo’;

x. To decrease the price of product by 20 of manufacturer ‘XYZ’.


update PRODUCT set Price=Price-20 where Manufacturer=’XYZ’;

xi. To print P_ID, ProductName, price and price of 12 items as BunchPrice.


select P_ID, ProductName,Price, Price*12 as BunchPrice from PRODUCT;

xii. To print details of product with null manufacturer.


select * from PRODUCT where Manufacturer is null;

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

You might also like