0% found this document useful (0 votes)
77 views

Listofpractical 22 23

The document contains details of 20 Python programming practicals to be completed by a Class XII student. Some key practicals include: 1. Functions to check if a number or string is a palindrome. 2. Linear search and binary search algorithms. 3. Sorting algorithms like bubble sort. 4. Reading and analyzing text files to count characters. 5. Calculating trigonometric functions like sine using Taylor series. 6. Working with lists, files, and object serialization using pickle. The practicals cover a range of Python programming concepts like functions, algorithms, file handling, and data structures.

Uploaded by

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

Listofpractical 22 23

The document contains details of 20 Python programming practicals to be completed by a Class XII student. Some key practicals include: 1. Functions to check if a number or string is a palindrome. 2. Linear search and binary search algorithms. 3. Sorting algorithms like bubble sort. 4. Reading and analyzing text files to count characters. 5. Calculating trigonometric functions like sine using Taylor series. 6. Working with lists, files, and object serialization using pickle. The practicals cover a range of Python programming concepts like functions, algorithms, file handling, and data structures.

Uploaded by

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

NAME=Urvashi Rao

Class=XII-A
ROLL NO.=12144
Session=2022-23
PRACTICAL FILE
COMPUTER
SCIENCE
PRACTICAL FILE- COMPUTER SCIENCE (083)
LIST OF PRACTICALS (2022-23) CLASS-XII
Programming Language : Python
S.
No.
NAME OF PRACTICAL

1. Write a program using function in python to check a number


whether it is prime or not.
def fact(no):
c=0
for i in range(1,no+1):
if no%i==0:
c=c+1
if c==2:
print("the number is prime:")
else:
print("the number is not prime:")
n=int(input("enter number:"))
ans=fact(n)

2. Write a program using function to check a number and string


whether it is palindrome or not.
def palindrome(str,n):
n=s(n)
if str==str[::-1] and n==n[::-1]:
print('both number and string are palindrome')
elif str==str[::-1] and n!=n[::-1]:
print('string is palindrome but number is not')
elif str!=str[::-1] and n==n[::-1]:
print('number is palindrome but string is not')
else:
print('both number nad string are not palindrome')
str=input('enter string:')
n=int(input('enter number:'))
palindrome(str,n)
3. Write a program for linear search.
def lsearch(l):
pos=-1
n=int(input("enter no:"))
for i in range(len(l)):
if l[i]==n:
pos=i
break
return pos
l=eval(input("enter list"))
ans=lsearch(l)
print(ans)

4. Write a program using function to display ASCII code of a


character and vice versa.
def display(char,code):
print(char,'->',ord(char))
print(code,'->',ord(code))
char=input('enter character: ')
code=int(input('enter ASCII code: '))
display(char,code)
5. Write a program using function to input a character and to print
whether a given character is an alphabet, digit or any other
character.
def func(char):
if char.isdigit():
print('digit')
elif char.isalpha():
print('alphabet')
else:
print('special character')
char=input('enter character: ')
func(char)

6. Write a program to generate random numbers between 1 to 6


and check whether a user won a lottery or not.
def check(n):
import random
win=random.randint(1,6)
if win==n:
print('you won')
else:
print('you lost')
n=int(input("enter lottery number:"))
check(n)
7. Write a program using function to print fibonacci series .
def fib(n):
a=0
b=1
print(a,",",b)
for i in range(2,n+1):
c=a+b
print(c)
a=b
b=c
n=int(input("no of terms:"))
fib(n)
8. Write a program using function for binary search on sorted list.
def binarysearch(ar,key):
low=0
high=len(ar)-1
while low<=high:
mid=int((low+high)/2)
if key==ar[mid]: #middle value 28
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
ar=[12,15,21,25,28,32,33,36,43,45] #sorted list
item=int(input("enter search item"))
res=binarysearch(ar,item) #fn calling
if res>=0:
print(item,"Found a index",res)
else:
print("sorry!",item ,"not found in the array")
9. Write a program for bubble sort.
def bubblesort(l):
for i in range(len(l)):
for j in range(len(l)-i-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
l=eval(input("enter list"))
bubblesort(l)
print(l)

10. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
def Count():
f=open('abc.txt')
cv=cc=cu=cl=0
s=f.read()
for i in s:
if i.isupper():
cu+=1
else:
cl+=1
if i in 'aeiouAEIOU':
cv+=1
else:
cc+=1
print('no of vowels:',cv)
print('no of consonants:',cc)
print('no of uppercase char:',cu)
print('no of lowercase char:',cl)
f.close()
Count()
11. Write a function in PYTHON to count and display the number
of words starting with alphabet ‘A’ or ‘a’ present in a text file
“LINES.TXT”.
Example:
If the file “LINES.TXT” contains the following lines,
“A boy is playing there. There is a playground. An aeroplane is
in the sky.Are you getting it?”
The function should display the output as 5.
def count():
c=0
with open("lines.txt") as f:
for ch in f:
ch=ch.split()
for word in ch:
if word[0]=='A' or word[0]=='a':
c+=1
print (c)
count()

12. Write a program to count number of words in a file.


f1=open("abc.txt","r")
s=f1.read()
l=s.split(" ")
print(len(l))
f1.close()
Write a python program using function sin(x,n) to calculate the value of sin(x) using
13. its taylor series expansion up to n terms.

def fact(no):
f=1
for i in range(no,0,-1):
f=f*i
return f
def sin(x,n):
s=0
f=1
p=0
k=-1
for i in range(3,n+1):
f=fact(i)
s=s+(x**i)/f
k=-k
return s
n1=int(input("enter first no:"))
n2=int(input("enter second no:"))
ans=sin(n1,n2)
print(ans)

14. Write a python code to find the sum of all elements of a list
those which are divisible by 7.
def sum(l):
s=0
for i in l:
if i%7==0:
s+=i
print('sum: ',s)
l=[]
x=int(input('”enter length of list:”))
for i in range(x):
n=int(input(“enter number:”))
l.append(n)
sum(l)

15. Write the function definition for WORD4CHAR() in PYTHON


to read the content of a text file FUN.TXT, and display all those
words, which have four characters in it.
Example:
If the content of the file Fun.TXT is as follows:
“When I was a small child, I used to play in the garden with my
grand mom. Those days were amazingly funful and I remember
all the moments of that time”
The function WORD4CHAR() should display the following:
“When used play with days were that time”

def wordchar():
f=open("fun.txt")
for ch in f:
ch=ch.split()
for word in ch:
if word[-1] in ".,:;":
word = word[:-1]
if len(word)==4:
print(word)
f.close()
wordchar()
16. Write a definition for function BUMPER() in PYTHON to read
each object of a binary file GIFTS.DAT, find and display details
of those gifts, which have remarks as “ON DISCOUNT”.
Assume that the file GIFTS.DAT is created with the help of lists
of following type:
(ID, Gift, Remarks, Price)

def BUMPER():
import pickle
f=open('GIFTS.dat','rb')
try:
while True:
record=pickle.load(f)
if record[2]=='ON DISCOUNT':
for i in record:
print(i,end=' ')
except:
pass
f.close()
BUMPER()
17. Create a binary file with name and roll number. Search for a
given roll number and display the name, if not found display.

def bin():
import pickle
f=open('abc.dat','ab')
for i in range(5):
name=input('enter name:')
r_no=int(input('enter roll no:”))
record={r_no:name}
pickle.dump(record,f)
f.close()
def search():
import pickle
r_no = int(input(“enter roll no to search:”))
f=open('abc.dat','rb')
flag=False
try:
while True:
record=pickle.load(f)
if r_no in record:
print(record[r_no])
flag=True
except:
pass
f.close()
if not flag:
print('not found')
bin()
search()
18. Create a binary file with roll number, name and marks. Input a
roll number and update the marks.
def create():
import pickle
f=open('ndata.dat','wb')
for i in range(3):
name=input('enter name:')
r_no=int(input('enter roll no:'))
marks=int(input('enter marks: '))
record=[r_no,name,marks]
pickle.dump(record,f)
f.close()
def modify():
import pickle,os
r_no = int(input('rnter roll no to search: '))
f=open('ndata.dat','rb')
t=open('temp.dat','wb')
flag=False
try:
while True:
record=pickle.load(f)
if record[0]==r_no:
nm=int(input('enter marks: '))
record[2]=nm
flag=True
pickle.dump(record,t)
except:
pass
f.close()
t.close()
if not flag:
print('not found')
os.remove('ndata.dat')
os.rename('temp.dat','ndata.dat')
create();modify()
19. Following is the structure of each record in a data file named
”PRODUCT.DAT”.
{"prod_code":value, "prod_desc":value, "stock":value}
The values for prod_code and prod_desc are strings, and the
value for stock is an integer. Write a function in PYTHON to
update the file with a new value of stock. The stock and the
product_code, whose stock is to be updated, are to be input
during the execution of the function.
def update_pro():
import pickle,os
temp=open("file.tmp",'wb')
with open("PRODUCT.DAT",'rb') as f:
pc=input("enter product code: ")
st=int(input(eEnter stock: "))
found=0
while(1):
try:
rec=pickle.load(f)
if rec['prod_code']==pc:
rec['stock']=st
found=1
pickle.dump(rec,temp)
except:
break
temp.close()
if found==0:
print("record not found")
else:
os.remove("product.dat")
os.rename("file.tmp","product.dat")
print("record updated")
20. Write a program to perform read and write operation with .csv
file.
def func():
import csv
f=open('data.csv','w',newline='')
wtr=csv.writer(f)
for i in range(5):
user_id=input('enter ID: ')
pwd=input('enter PWD: ')
wtr.writerow([user_id,pwd])
f.close()
def read():
import csv
f=open('data.csv')
rdr=csv.reader(f)
for i in rdr:
print(i[0],i[1],sep='=>')
f.close()
func()
read()
21. Write a menu based program to perform the operation on stack
in python.
stack=[]
def push():
n=int(input(“enter number:”))
stack.append(n)
print('value added successfully')
def isEmpty():
return len(stack)==0
def pop():
if isEmpty():
print('underflow-stack is empty')
return
stack.pop()
def display():
for i in range(-1,-1-len(stack),-1):
print(stack[i])
def mainmenu():
import sys
while True:
print('1.push')
print('2.pop')
print('3.display')
print('4.exit')
choice=input('enter choice[1-4]: ')
if choice.isdigit():
choice=int(choice)
else:
print('invalid choice')
continue
if choice==1:
push()
elif choice==2:
pop()
elif choice==3:
display()
elif choice==4:
sys.exit()
else:
print('invalid choice')
mainmenu()
22. 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.
def Fetch()
import mysql.connector as sql
con=sql.connect(host='localhost',user='root',passwd='1234',db='ncjps')
cur=con.cursor()
query='select * from employee'
cur.execute(query)
data=cur.fetchall()
for row in data:
print(row)
con.close()
def Update():
import mysql.connector as sql
con=sql.connect(host='localhost',user='root',passwd='1234',db='ncjps')
cur=con.cursor()
ns=int(input('Enter New Salary: '))
empno=int(input('Enter Employee Number: '))
query='update employee set salary={} where empno ={}'.format(ns,empno)
cur.execute(query)
con.commit()
con.close()
def Delete():
import mysql.connector as sql
con=sql.connect(host='localhost',user='root',passwd='1234',db='ncjps')
cur=con.cursor()
empno=int(input('Enter Employee Number: '))
query='delete from employee where empno={}'.format(ns,empno)
cur.execute(query)
con.commit()
con.close()
Fetch()
Update()
Delete()

23. Consider the following tables STORE and SUPPLIERS and answer (a)
and (b) parts of this question:
Table: - Store
ItemNo. Iteam Scode Qty Rate LastBuy
2005 Sharpener Classic 23 60 8 31-Jun-09
2003 Ball Pen 0.25 22 50 25 01-Feb-10
2002 Gel Pen Premium 21 150 12 24-Feb-10
2006 Gel Pen Classic 21 250 20 11-Mar-09
2001 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09

Table:- Supplier
Scode Sname
21 Premium Stationers
23 Soft Plastics
22 Tetra Supply
A.Write SQL commands for the following statements:
(i) To display details of all the items in the Store table in ascending
order of LastBuy.

SELECT * FROM STORE ORDER BY LastBuy;

(ii) To display ItemNo and Item name of those items from Store
table, whose Rate is more than 15 Rupees.

SELECT ItemNo,Item FROM STORE WHERE RATE>15;

(iii) To display the details of those items whose Supplier code (Scode)
is 22 or Quantity in Store (Qty) is more than 110 from the table
Store.
SELECT * FROM STORE A,SUPPLIER B WHERE A.Scode=22 AND Qty>110;

(iv) To display Minimum Rate of items for each Supplier individually


as per Scode from the table Store.

SELECT MIN(Rate) FROM ITEM GROUP BY Scode;

B.Give the output of the following SQL queries:


(v) SELECT COUNT(DISTINCT Scode) FROM Store;
COUNT(DISTINCT Scode)

23
22
21

(vi) SELECT Rate*Qty FROM Store WHERE ItemNo=2004;


Rate*Qty
480
1250
1800
5000
1320
880
3240

(vii) SELECT Item,Sname FROM Store S, Suppliers P WHERE


S.Scode=P.Scode AND ItemNo=2006;

Item Sname
Gel Pen Classic Premium Stationers

(iv)SELECT MAX(LastBuy) FROM Store;

MAX(LastBuy)
24-Feb-10

24. Consider the following table Item and Customer.


Table:- ITEM
i_ID ItemName Manufacturer Price
PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
Pc03 Personal Computer XYZ 32000
Pc06 Personal Computer COMP 37000
Lc03 Laptop PQR 57000

Table : CUSTOMER
C_ID CustomerName City I_ID
01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Banglore PC01

A.Write SQL commands for the following statements:

I. To display the details of those Customer whose City is Delhi.

SELECT * FROM Customer WHERE City=’Delhi’;

II. To display the details of Item whose Price is in the range of


3500 to 55000 (Both values included).

SELECT * FROM ITEM WHERE PRICE BETWEEN 3500 AND


55000;

III. To display the CustomerName, City from table Customer,


and ItemName and Price from table Item with their
corresponding matching I_ID.
SELECT * FROM CustomerName,City,ItemName,Price From ITEM A,
Price B WHERE A.I_ID=B.I_ID;

IV. To increase the Price of all Items by 1000 in the table Item.

UPDATE ITEM SET PRICE=PRICE+1000;

B.Give the output of the following SQL queries:

V. SELECT DISTINCT City FROM Customer;


City
Delhi
Mumbai
Banglore

VI. SELECT ItemName, Max(Price), Count(*) FROM Item


GROUP BY ItemName;
ItemName |Max(Price)|Count(*)
PERSONAL COMPUTER|37000|3
LAPTOP| 57000|2

VII. SELECT CustomerName, Manufacturer From Item, Customer


WHERE Item.I_Id=Customer.I_Id;
CustomerName|Manufactuer
Personal Computer|ABC
Laptop|ABC
Personal Computer|XYZ
Personal Computer|COMP
Laptop|PQR

VIII. SELECT ItemName, Price * 100 FROM Item WHERE


Manufacturer = ‘ABC’;
Item Name|Price*100
Personal Computer|3500000
Laptop|5500000

25. Consider the following tables.


TABLE : SENDER
SenderID SenderName SenderName SenderCity
ND01 R Jain 2,ABC Appts New Delhi
MU02 H Sinha 12, Newtown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K, SDA New Delhi

TABLE : RECIPIENT

SenderID RecName RecAddress ReCity


KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mohan 116, A vihar New Delhi
MU19 ND01 H singh 2a, Andheri east Mumbai
MU32 MU15 P K Swamy B5, c S Terminus Mumbai
ND48 ND50 S Tirupathi 13, B1 d, Mayur New Delhi
vihar

A.Write SQL commands for the following statements:

I. To display the names of all Senders from Mumbai.

Select * from Sender where SenderCity =’Mumbai’;

II. To display the RecID, SenderName, SenderAddress,


RecName, RecAddess for every Recipient

SELECT RecID,SenderName,SenderAddress,RecName,RecAddress FROM


SENDER A,RECIPIENT B WHERE A.SenderID=B.SenderID;

III. To display Recipient detail in ascending order of RecName

SELECT * FROM RECIPIENT ORDER BY RecName;

IV. To display number of Recipients from each city

SELECT COUNT(*) FROM RECIPIENT GROUP BY ReCity;

B.Give the output of the following SQL queries:

V. SELECT DISTINCT Sendercity FROM Sender;

SenderCity
Kolkata
New Delhi
Mumbai
VI. SELECT A.SenderName A, B.RecName FROM Sender A,
Recipient B WHERE A.SenderID=B. SenderID AND
B.RecCity=’Mumbai’;

 SenderName     RecName
R.Jain H. Singh
S Jha P.K. Swamy

VII. SELECT RecName,RecAddress FROMRecipient WHERE


RecCity Not IN (‘Mumbai’,Kolkata’);

RecName      RecAddressS
   Mahajan         116, A Vihar
   S Tripati          13, B1 D, Mayur Vihar
VIII. SELECT RecID, RecName FROM Recipient WHERE
SenderID = ‘MU02’ OR SenderID = ‘ND50’;

 RecID         RecName
  ND08         S Mahajan
   ND48         S Tripat

26. Consider the following tables FURNITURE and ARRIVALS: write SQL
commands for the questions (a) to (f) and give outputs for SQL queries (i)
to (iv) :
TABLE : FURNITURE
NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White lotus Double Bed 23/02/02 30000 25
2 Pink feather Baby cot 20/01/02 7000 20
3 Dolphin Baby cot 19/02/02 9500 20
4 Decent Office Table 01/01/02 25000 30
5 Comfort zone Double Bed 12/01/02 25000 25
6 Donald Baby cot 24/02/02 6500 15
7 Royal Finish Office Table 20/02/02 18000 30
8 Royal tiger Sofa 22/02/02 31000 30
9 Econo sitting Sofa 13/12/01 9500 25
10 Eating Paradise Dining 19/02/02 11500 25
Table
TABLE : ARRIVALS
NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
11 Wood Comfort Double Bed 23/03/03 25000 25
12 Old Fox Sofa 20/02/03 17000 20
13 Micky Baby cot 21/02/03 7500 15

A.Write SQL commands for the following statements:

a) To show all information about the Baby cots from the


FURNITURE table.

SELECT*FROM FURNITURE WHERE TYPE=’BABY COT’;

b) To list the ITEMNAME which are priced at more than 15000


from the FURNITURE

SELECT ITEM_NAME FROM FURNITURE WHERE


PRICE>15000;

c) To list ITEMNAME and TYPE of those items, in which


DATEOFSTOCK is before 22/01/02 from the FURNITURE
table in descending order of ITEMNAME.

SELECT ITEM_NAME,TYPE FROM FURNITURE WHERE


DOS<’22-JAN-02’ORDER BY ITEM_NAME DESC;

d) To display ITEMNAME and DATEOFSTOCK of those items,


in which the DISCOUNT percentage is more than 25 form
FURNITURE table.

SELECT ITEM_NAME,DOS FROM FURNITURE WHERE


DISCOUNT>25;

e) To count the number of items, whose TYPE is “Sofa” from


FURNITURE table.

SELECT COUNT(*)FROM FURNITURE WHERE


TYPE=’SOFA’;

f) To insert a new row in the ARRIVALS table with the


following data:
14, ‘Velvet touch’, ‘Double bed’, {25/03/03}, 25000,30
Insert into arrival values(14,’velvet touch’,’double bed’,’25-
MAR-03’,25000.00,30);

B.Give the output of following SQL statement:


NOTE : Outputs of the below mentioned queries should be based on original data given
in both the tables, i.e., without considering the insertion done in (f) part of this question :
I. Select COUNT (distinct TYPE) from FURNITURE;
5

II. Select MAX(DISCOUT) form FURNITURE, ARRIVALS;


30

III. Select AVG(DISCOUT) form FURNITURE where TYPE = ‘Baby


cot’;

18.3333

IV. Select SUM(PRICE) from FURNITURE where


DATEOFSTOCK<{12/02/02};
66500

27. Study the following tables DOCTOR and SALARY and write SQL
commands for the questions (i) to (iv) and give outputs for SQL queries
(v) to (vi) :

TABLE : DOCTOR
ID NAME DEPT SEX EXPERIENCE
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15
TABLE : SALARY
ID BASIC ALLOWANCE CONSULTATION
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300
A.Write SQL commands for the following statements:

(i) Display NAME of all doctors who are in “MEDICINE” having more
than 10 year experience from the table DOCTOR.

Select Name from Doctor where Dept=”Medicine” and Experience>10

(ii)Display the average salary of all doctors working in “ENT”


department using the tables DOCTOR and SALARY.
Salary=BASIC + ALLOWANCE.

 Select avg(basic+allowance) from Doctor,Salary where Dept=”Ent” and


Doctor.Id=Salary.Id
(iii) Display the minimum ALLOWANCE of female doctors.

Select min(Allowance) from Doctro,Salary where Sex=”F” and


Doctor.Id=Salary.Id

(iv) Display the highest consultation fee among all male doctor

Select max(Consulation) from Doctor,Salary where Sex=”M” and


Doctor.Id=Salary.Id
B.Give the output of following SQL statement:

(v) SELECT count(*) from DOCTOR where SEX=”F”.


4

(vi) SELECT NAME, DEPT, BASIC from DOCTOR Salary WHERE


DEPT=”ENT” AND DOCTORID=SALARY.ID
  Name           Dept Basic
  Jonah Ent        12000

You might also like