0% found this document useful (0 votes)
187 views75 pages

Computer Practical

The document discusses a class project for students to create a tangible and useful program using Python file handling or SQL connectivity. It encourages students to find real-world problems to solve and be creative in their projects. It also advises avoiding plagiarism and copyright issues. The rest of the document provides programming questions and solutions related to functions, searching, sorting, stacks, and SQL connectivity.

Uploaded by

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

Computer Practical

The document discusses a class project for students to create a tangible and useful program using Python file handling or SQL connectivity. It encourages students to find real-world problems to solve and be creative in their projects. It also advises avoiding plagiarism and copyright issues. The rest of the document provides programming questions and solutions related to functions, searching, sorting, stacks, and SQL connectivity.

Uploaded by

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

PRACTICAL PROGRAMS WITH SOLUTION

COMPUTER SCIENCE - XII

1
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROJECT:
The aim of the class project is to create something that is tangible and useful using Python
file handling/ Python-SQL connectivity. This should be done in groups of two to three
students and should be started by students at least 6 months before the submission
deadline. The aim here is to find a real world problem that is worthwhile to solve.

Students are encouraged to visit local businesses and ask them about the problems that
they are facing. For example, if a business is finding it hard to create invoices for filing
GST claims, then students can do a project that takes the raw data (list of transactions),
groups the transactions by category, accounts for the GST tax rates, and creates invoices
in the appropriate format. Students can be extremely creative here. They can use a wide
variety of Python libraries to create user friendly applications such as games, software for
their school, software for their disabled fellow students, and mobile applications, of course
to do some of these projects, some additional learning is required; this should be
encouraged. Students should know how to teach themselves.

The students should be sensitized to avoid plagiarism and violations of copyright issues while
working on projects. Teachers should take necessary measures for this.

2
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

INDEX

QUESTION
S.NO TITLE PAGE NO
NO

1 PY-1 WORKING WITH FUNCTIONS: SUM OF SERIES 5

WORKING WITH FUNCTIONS: SUM OF PRIME, PERFECT AND


2. PY-2 8
ARMSTRONG NUMBERS

3. PY-3 WORKING FUNCTIONS: BINARY SEARCH, LINEAR SEARCH 10

WORKING WITH FUNCTIONS : SORTING – BUBBLE ,


4. PY-4 13
INSERTION SORT

5. PY-5 WORING WITH MODULE : SIMULATES A DICE 16

6. PY-6 TEXT FILE HANDLING: CHARACTER, LINE, WORD COUNT 17

7. PY-7 TEXT FILE HANDLING: FREQUENCY OF WORDS 19

8. PY-8 TEXT FILE HANDLING: COPYING FILE 21

9. PY-9 CSV FILE: WRITING, READING, SEARCHING 24

10. PY-10 CSV FILE: COPYING FILE 27

11. PY-11 BINARY FILE: WRITING, READING 31

3
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

12. PY-12 BINARY FILE: SEARCHING AND UPDATING 35

13. PY-13 BINARY FILE: DELETING 39

14. PY-14 STACK - PUSH, POP, PEEK, DISPLAY USING LIST 43

15. PY-15 STACK – PUSH, POP, PEEK, DISPLAY USING DICTIONARY 46

16. PY-SQL-1 CONNECTIVITY: INSERT AND DISPLAY TABLE CONTENT 49

17. PY-SQL-2 CONNECTIVITY: ALTER TABLE, UPDATING 53

18. PY-SQL-3 CONNECTIVITY: DELETING 56

19. PY-SQL-4 CONNECTIVITY: USING GROUP BY CLAUSE,JOIN 57

20. SQL-1 SQL COMMANDS - 1 62

21. SQL-2 SQL COMMANDS - 2 65

22. SQL-3 SQL COMMANDS - 3 68

23. SQL-4 SQL COMMANDS - 4 70

24 SQL-5 SQL COMMANDS - 5 72

4
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Program 1: WORKING FUNCTIONS : SUM THE SERIES


AIM: Program to sum the series using functions :
a. 1+1/1!-2/2!+3/3!-4/4!+......+-n/n!
b. Sum the Fibonacci series up to n terms

SOURCE CODE:

def sumfib(n):
s=0
f1=-1
f2=1
for i in range(n):
f3=f1+f2
print(f3,end="+")
s=s+f3
f1=f2
f2=f3
return s

def fact(n):
f=1
for i in range(1,n+1):

5
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

f=f*i
return f
c=1
while c:

print("1. To sum series 1+1/1!-2/2!+3/3!...")


print("2. To sum fibonacci series")
print("0. to Exit")
c=int(input("Enter your choice"))

if c==1:
x=int(input("Enter nth term"))
s=1
for i in range(1,x+1):
if i%2!=0:
s=s+i/fact(i)
else:
s=s-i/fact(i)
print("sum of the series =",s)
if c==2:
x=int(input("Enter nth term"))
y=sumfib(x)

6
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("=",y)
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS VERIFIED SUCCESSFULLY

7
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Program 2: WORKING WITH FUNCTIONS: SUM PRIME,


PERFECT, ARMSTRONG NUMBERS
AIM:
A menu driven program using functions a. To sum all prime
numbers up to n b. To sum all 3 digits Armstrong numbers c. To
sum all perfect numbers from 100 to 1000
SOURCE CODE:
def prime(n):
s=0
for i in range(1,n+1):
f=0
for j in range(2,i//2+1):
if i%j ==0:
f=f+1
if f==0:
s=s+i
return s
def armstrong():
s=0
for i in range(100,1000):
n=i
s1=0
while n!=0:
d=n%10
s1=s1+d**3
n=n//10
if s1==i:
print(i,end=" ")
s=s+i
return s
def perfect():
8
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

s=0
for i in range(100,1000):
s1=0
for j in range(1,i//2+1):
if i%j ==0:
s1=s1+j
if s1==i:
s=s+i
return s
c=1
while c:
print("1. To sum prime numbers up to n terms")
print("2. To sum Armstrong numbers")
print("3. To sum perfect numbers")
print("0. To Exit")
c=int(input("Enter your choice"))
if c==1:
x=int(input("Enter nth term"))
y=prime(x)
print(" sum =",y)

if c==2:

y=armstrong()
print("sum=",y)
if c==3:
y= perfect()
print("sum=",y)

OUTPUT:
RESULT: Thus the above program is executed and output is verified
successfully
9
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Program 3 : WORKING WITH FUNCTIONS : Linear Search ,


Binary Search
AIM:

To Write a python code using functions to search an element in a list i) using


Linear search ii) using binary search techniques.

SOURCE CODE:

def lsearch(l,e):
for i in range(len(l)):
if l[i]==e:
return i
else:
return -1

def bsearch(l,e):
lb=0
ub=len(l)-1
while lb<=ub:

mid =(lb+ub)//2
if e== l[mid]:
10
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

return mid
elif e >l[mid]:
lb=mid+1
else :
ub=mid-1
return -1
c=1
while c:
print("1. Search an Element using Linear search")
print("2. Search an Element using Binary search")
print("0. To Exit")
c=int(input("Enter your choice"))
if c==1:
l=eval(input("Enter the List"))
print("Content of List")
print(l)
x=int(input("Enter Element to search" ))
y=lsearch(l,x)
if y !=-1:
print( x,"Found at ",y,"Postion")
else:
print(x, "Not Found in the list")

11
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if c==2:
x=eval(input("enter a list"))
x.sort()
print("original List")
print(x)
y=int(input("Enter element to search"))
r=bsearch(x,y)
if r==-1:
print(y, "Not found in the list")
else:

print(y,"Found at",r, "position")

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY
12
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 4: WORKING WITH FUNCTIONS


AIM:

To write a python code using functions i) accept list and print original list ii) Sort
list in ascending order using bubble sort iii) sort list in descending order using
insertion sort.

SOURCE CODE:

l=[]
c=1
def bsort(l):
n=len(l)
for i in range(n):
for j in range(n-i-1):
if l[j]>l[j+1]:
l[j+1],l[j]=l[j],l[j+1]
return l

def isort(l):
for i in range(len(l)):
j=i-1
t=l[i]
13
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

while j >=0 and t>l[j]:


l[j+1]=l[j]
j=j-1
l[j+1]=t
return l

c=1
while c:
print("1.Store data in the list")
print("2.Sort using Bubble sort")
print("3.Sort using insertion sort")
print("0. exit")
c=int(input("Enter your choice"))
if c==1:
l= eval(input("Enter the list"))

if c==2:
print("original List")
print(l)
l=bsort(l)
print("Sorted list")
print(l)

14
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if c==3:
print("original List")
print(l)
l=isort(l)
print("Sorted list")
print(l)

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

15
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRM 5: WORKING WITH MODULES


AIM:
Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice) and count number
of time each number is generated in 20 toss.
Source code:
import random as r
d={}
n = int (input("No of toss"))
for i in range(n):
rn=r.randint(1,6)
if rn not in d:
d[rn]=1
else:
d[rn]+=1
print(d)
print ( " No\t\t Frequency")
s=sorted(d.items())
for i in s:
print (i[0],"\t\t",i[1])
OUTPUT:

16
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND


OUTPUT IS VERIFIED SUCCESSFULLY
PROGRAM 6: WORKING WITH TEXT FILES
AIM:
To Write a program to i) create a text file ii) display content of file, display line
count, word count, character count of the created file.

SOURCE CODE:

def createfile():
f=open("text.txt","w")
n=int(input("enter Number of lines"))
for i in range(n):
x=input("Enter a line")
f.write(x+"\n")
f.close()
def readandcount():
f=open("text.txt","r")
x=f.readlines()
lc=len(x)
f.seek(0,0)
x=f.read()
x1=x.split()

17
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

wc=len(x1)
cc=len(x)
print("content of file")
print(x)
print("Line count :",lc)
print("Word count :",wc)
print("character count :",cc)
c=1
while c:
print("1.To create Text file")
print("2.To display file and display line,word, character count")
print("0 To Exit")
c=int(input("Enter your choice"))
if c==1:
createfile()
elif c==2:
readandcount()
OUTPUT:

18
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND


OUTPUT IS VERIFIED SUCCESSFULLY

19
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 7: WORKING WITH TEXT FILES


AIM:

To Write a python script i) to create text file ii) To display the file iii) to find
display all repeated words with their word count.

def createfile():
f=open("test.txt","w")
n=input("Enter a string")
f.write(n)
f.close()
def readfile():
d={}
f=open("test.txt","r")
x=f.read()
f.close()
print("Content of file")
print("======================")
print(x)
print("======================")
for i in x.split():
if i not in d:

20
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

d[i]=1
else:
d[i]=d[i]+1
print("Frequency of words")
print("======================")
for i in d:
print(i,'\t',d[i])
print("======================")
c=1
while c:
print("1.To Create Text file")
print("2.To Display file and Repeated words")
print("0. Exit ")

c=int(input("Enter your choice"))


if c==1:
createfile()
elif c==2:
readfile()
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY
21
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 8: WORKING WITH TEXT FILES


AIM:

To Write a python script i) to create a text file “Source.txt” having number of


lines ii) copy source.txt into another file target.txt after converting first character
of each word of each line to uppercase iii) display original and target file.

SOURCE CODE:

def createfile():
f=open("source.txt","w")
n=int(input("enter Number of lines"))
for i in range(n):
x=input("Enter a line")
f.write(x+"\n")
f.close()
def readfile():
f=open("source.txt","r")
x=f.readlines()
print("Content of source file")
print("======================")
for i in x:
print(i,end='')
f.close()
22
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

f1=open("target.txt","r")
x=f1.readlines()
print("Content of target file")
print("======================")
for i in x:
print(i,end='')
f1.close()

def writefile():
f=open("source.txt","r")
f1=open("target.txt","w")
x=f.readlines()
for i in x:
t=i.title()
f1.write(t)

f.close()
f1.close()
print("Target file created, press enter to continue...")
x=input()
c=1

23
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

while c:
print("1.To create Source file")
print("2.To create Target file")
print("3.To display files")
print("4.To Exit ")
c=int(input("Enter your choice"))
if c==1:
createfile()
elif c==2:
writefile()
elif c==3:
readfile()
elif c==4:
break
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

24
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 9: WORKING WITH CSV FILES


AIM:

To Write a python script i) to create csv file telephone.csv consist of rollno,


name, telephone number of n students ii) display the created file iii) search for a
telephone number and display corresponding rollno and name. If telephone
number , not found display the message “not found”

SOURCE CODE:

import csv
def createcsv():
f=open("telephone.csv","w",newline="")
mywriter=csv.writer(f,delimiter=',')
n=int(input("Enter number of records"))
for i in range(1,n+1):
rno = input(" Enter Roll Number")
name=input("Enter Name ")
tn=input("Enter Telephone Number")
row=[rno,name,tn]
mywriter.writerow(row)
f.close()
def readcsv():

25
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

f=open("telephone.csv","r")
ro=csv.reader(f)
print("==========================================")
print("%-10s"%"Rno","%-20s"%"Name","%-
10s"%"Telephone Number")
print("==========================================")

for i in ro:
print("%-10s"%i[0],"%-20s"%i[1],"%-10s"%i[2])
print("==========================================")
f.close()
def search(tn):
f=open("telephone.csv","r")
ro=csv.reader(f)
for i in ro:
if i[2]==tn:
print( "Roll No ------------:",i[0])
print("Name ------------:",i[1])
print("Telephone ------------:",i[2])
return True
return False
c=1
while c:
26
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("1.To create csv file")


print("2.To Display file")
print("3.To Search Telephone Number")
print("4.To Exit ")
c=int(input("Enter your choice"))
if c==1:
createcsv()
elif c==2:
readcsv()
elif c==3:
tn=input("Enter Telephone number to search")
found=search(tn)
if not found :
print(tn, " Not Found")
elif c==4:
break
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

27
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 10: WORKING WITH CSV FILES


AIM:
To write a python script i) to crate csv file student.csv having rollno, name,
marks ii) display file iii) copy marks of passed students in pass.csv and failed
students in fail.csv iv) display files pass.csv and fail.csv

SOURCE CODE:
import csv
def createcsv():
f=open("student.csv","w",newline="")
mywriter=csv.writer(f,delimiter=',')
n=int(input("Enter number of records"))
for i in range(1,n+1):
rno = input(" Enter Roll Number")
name=input("Enter Name ")
mark=input("Enter Marks")
row=[rno,name,mark]
mywriter.writerow(row)
f.close()
def displaycsv():
f=open("student.csv","r")
ro=csv.reader(f)
print("==========================================")
print("%-10s"%"Rno","%-20s"%"Name","%-10s"%"Marks")

28
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("==========================================")

for i in ro:
print("%-10s"%i[0],"%-20s"%i[1],"%-10s"%i[2])
print("==========================================")
f.close()
def createpfcsv():
f=open("student.csv","r")
f1=open("pass.csv","w",newline="")
f2=open("fail.csv","w",newline="")
mywriter1=csv.writer(f1,delimiter=',')
mywriter2=csv.writer(f2,delimiter=',')
ro=csv.reader(f)
for i in ro:
row=[i[0],i[1],i[2]]
if int(i[2]) >=33:
mywriter1.writerow(row)
else:
mywriter2.writerow(row)
f.close()
f1.close()
f2.close()

29
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

def displaypffile():
f=open("pass.csv","r")
ro=csv.reader(f)
print("Passed Students")
print("=============")
print("==========================================")
print("%-10s"%"Rno","%-20s"%"Name","%-10s"%"Marks")
print("==========================================")
for i in ro:
print("%-10s"%i[0],"%-20s"%i[1],"%-10s"%i[2])
print("==========================================")
f.close()
f1=open("Fail.csv","r")
ro=csv.reader(f1)
print("Failed Students")
print("=============")
print("==========================================")
print("%-10s"%"Rno","%-20s"%"Name","%-10s"%"Marks")
print("==========================================")
for i in ro:
print("%-10s"%i[0],"%-20s"%i[1],"%-10s"%i[2])
print("==========================================")

30
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

f1.close()
c=1
while c:
print("1.To create csv file")
print("2.To Display Original File")
print("3.To Create Pass and Fail File")
print("4.Display Pass and Fail File")
print("5.To Exit ")
c=int(input("Enter your choice"))
if c==1:
createcsv()
elif c==2:
displaycsv()
elif c==3:
createpfcsv()
elif c==4:
displaypffile()
elif c==5:
break
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

31
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

32
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 11: WORKING WITH BINARY FILES


AIM:

To Write a program i) to create binary file stud.dat having rollno, name, marks
ii) Display content of file ii) to display data in descending order of marks

SOURCE CODE:

import pickle
def create():
f=open("stud.dat","ab")
n=int(input("Enter number of students"))
for i in range(n):
rno=int(input("Enter Roll No"))
name=input("Enter Name")
marks=int(input("enter Marks"))
rec=[rno,name,marks]
pickle.dump(rec,f)
f.close()
def displayfile():
f=open("stud.dat","rb")

while True:
33
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

try:
rec=pickle.load(f)
print("Roll No--------------------:", rec[0])
print("Name---------------------:",rec[1])
print("Marks---------------------:",rec[2])
except:
break
f.close()
def descending():
f=open("stud.dat","rb")
l=[]
while True:
try:
rec=pickle.load(f)
l.append(rec)

except:
break
f.close()
n=len(l)
print(l)

34
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

for i in range(len(l)):
for j in range(len(l)-i-1):
if l[j][2]<l[j+1][2]:
l[j+1],l[j]=l[j],l[j+1]

print("Data is descending order")


print("===================")
print("==========================================")
print("%-10s"%"Roll no","%-30s"%" Name","%-20s"%"Marks")
print("==========================================")

for i in range(n):
print("%-10s"%l[i][0],"%-30s"%l[i][1],"%-20s"%l[i][2])
print("==========================================")

#driver code

while True:
print("1. Create Binary File")
print("2. Display File Content")
print("3. Display File in descending Order of Marks")
c=int(input("enter your choice, 0 to exit"))

35
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if c==1:
create()
if c==2:
displayfile()
if c==3:
descending()
if c==0:
break
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

36
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 12: WORKING WITH BINARY FILES


AIM:
To Write a program i) to create binary file emp.dat having empno, name, salary
ii) To update salary of specific employee by accepting empno. iii) to Display the
file

SOURCE CODE:

import pickle
import os
def create():
f=open("emp.dat","wb")
n=int(input("Enter number of employees"))
for i in range(n):
eno=int(input("Enter Employee No"))
name=input("Enter Name")
sal=int(input("Enter salary"))
rec=[eno,name,sal]
pickle.dump(rec,f)
f.close()
def displayfile():
f=open("emp.dat","rb")
print("==========================================")

37
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("%-10s"%"Empno","%-20s"%"Name","%-10s"%"Salay")
print("==========================================")

while True:
try:
rec=pickle.load(f)
print("%-10s"%rec[0],"%-20s"%rec[1],"%-10s"%rec[2])
print("==========================================")
except:
break
f.close()
def updaterec():
f=open("emp.dat","rb")
en=int(input("Enter Employee number whose salary to update"))
l=[]
fo=0
while True:
try:
rec=pickle.load(f)
if rec[0]==en:
print("Emp No--------------------:", rec[0])
print("Name---------------------:",rec[1])

38
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("Salary---------------------:",rec[2])
rec[2]=int(input("New salary"))
fo=1
l.append(rec)

except:
break
f.close()
if fo==1:
f=open("emp.dat","wb")
for i in l:
pickle.dump(i,f)
else:
print(en, "Not Found")
x=input("Press Enter to continue....")
f.close()
#driver code
while True:
print("1. Create Binary File")
print("2. Update Salary of an employee")
print("3. Display File ")
c=int(input("enter your choice, 0 to exit"))

39
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if c==1:
create()
if c==2:
updaterec()
if c==3:
displayfile()
if c==0:
break

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

40
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

PROGRAM 13: WORKING WITH BINARY FILES


AIM:

To Write a program i) to create binary file school.dat consist of affiliation no,


school name, Region ii) delete a record after displaying record and getting
confirmation from the user. iii) to display a records.

SOURCE CODE:
import os
import pickle
def create():
f=open("School.dat","ab")
n=int(input("Enter number of Schools"))
for i in range(n):
afno=int(input("Enter Affiliation No"))
sname=input("Enter School Name")
reg=input("Enter Region")
rec=[afno,sname,reg]
pickle.dump(rec,f)
f.close()
def displayfile():
f=open("school.dat","rb")
print("============================================")

41
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("%-10s"%"Schoolno","%-20s"%"SchoolName","%-
10s"%"Region")
print("=============================================")
while True:
try:
rec=pickle.load(f)
print("%-10s"%rec[0],"%-20s"%rec[1],"%-10s"%rec[2])

print("=============================================")
except:
break
f.close()
def delrec():
f=open("school.dat","rb")
f1=open("temp.dat","wb")
l=[]
while True:
try:
rec=pickle.load(f)
print("School No------------------------:", rec[0])
print("Scholl Name---------------------:",rec[1])
print("Region-----------------------------:",rec[2])
ch=input("Like to Delete this record y/n")
42
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if ch.lower()=='y':
continue
else:
pickle.dump(rec,f1)
except:
break
f.close()
f1.close()
os.remove("school.dat")
os.rename("temp.dat","school.dat")
#driver code

while True:
print("1. Create Binary File")
print("2. Delete Records")
print("3. Display File ")
c=int(input("enter your choice, 0 to exit"))
if c==1:
create()
if c==2:
delrec()
if c==3:

43
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

displayfile()
if c==0:
break

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

44
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

14. WORKING WITH STACKS- LIST


AIM:
Write a Python program to implement a stack using list.
# Program to implement stack using lists
#
l=[]
def push_elt(l,x):
l.append(x)
print("Element Inserted")
def pop_elt(l):
if l==[]:
print("Underflow!! Stack is empty")
else:
print(l.pop(),"is removed from stack")
def peek(l):
if l==[]:
print("Stack is empty")
else:
print("Element at top of stack is ......",l[len(l)-1])
def display(l):
if l ==[]:
print(" Stack is empty")

45
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

else:
print("Content of stack: ")

for i in range(len(l)):
print(l[i],end="->")
print()
while True:
print("1. Push Element into a Stack")
print("2. Pop Element from a Stack")
print("3. Peek Element from stack")
print("4. Display content of a stack")
print("5. Exit")
c=int(input("Enter your choice:"))
if c==1:
x=int(input("Enter element to push: "))
push_elt(l,x)
elif c==2:
pop_elt(l)
elif c==3:
peek(l)
elif c==4:
display(l)

46
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

elif c==5:
break
else:
print("Please enter the correct choice....")

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

47
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

15. WORKING WITH STACKS- DICTIONARY

AIM:
Write a program to implement a stack of book in a dictionary
{book no: book name}

Source code:
#Program to implement a stack of book details {book no: book
name}.
#
book=[]
def push_item(l,x):
l.append(x)
print("Element Inserted")
def pop_item(l):
if l==[]:
print("Underflow!! Stack is empty")
else:
print(l.pop(),"is removed from stack")
def peek(l):
if l==[]:
print("Stack is empty")
else:
48
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("Element at top of stack is ......",l[len(l)-1])


def display(l):
if l ==[]:
print(" Stack is empty")
else:
print("Content of stack: ")

for i in range(len(l)):
print(l[i],end="->")
print()

while True:
print("Stack operations for Book details")
print("-"*45)
print("1. Push book details")
print("2. Pop book details")
print("3. Peek book details")
print("4. Display book details")
print("5. Exit")
c=int(input("Enter your choice:"))
if c==1:
bno=int(input("Enter book no to be inserted: "))

49
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

bname=input("Enter book name to be inserted:")


item={bno:bname}
push_item(book,item)
elif c==2:
pop_item(book)
elif c==3:
peek(book)
elif c==4:
display(book)
elif c==5:
break
else:
print("Please enter the correct choice......")

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

50
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

16. CONNECTING MYSQL WITH PYTHON – 1


AIM:
Create a python application to
i) create database
ii) create table student(Rollno, Name, class, section, Mobile)
iii) Insert 5 rows
iv) Display content of a table
v) Display the structure of the table
'''Create a python application to
i) create database School
ii) create table student(Rollno, Name, class,Section, Mobile)
iii) Insert rows into the table
iv) Display content of a table using mysql connectivity with
python'''
import mysql.connector as sql
con=sql.connect(host="localhost",
user="root",passwd="",charset="utf8")
cur=con.cursor()
#Create database
cur.execute("create database if not exists School")
#Create Table
cur.execute("use School")
cur.execute("create table if not exists student(RollNo int(5) primary
key,\

51
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Name varchar(20), Class char(3), Section char(1), Mobile


varchar(10))")
print("Table student created successfully")
#inserting rows
def insert():
n=int(input("Enter Number of tuples to input [Enter 0 to insert
no rows] :"))
for i in range(n):
rno=int(input("Enter Roll number:"))
na=input("Enter Name of student:")
cla=input("Enter class:")
sec=input("Enter Section:")
mob=input("Enter Mobile number")
cur.execute("insert into student
values({},'{}','{}','{}','{}')".format(rno,na,cla,sec,mob))
con.commit()
#Displaying content of the table
def display():
print("CONTENT OF TABLE STUDENT")
print("="*40)
print()
cur.execute("select * from student")
print("RollNo\t Name \t Class \t Section \t Mobile")

52
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("*"*50)
for i in cur:
print (i[0]," "," ",i[1]," ",i[2],"\t",i[3],"\t\t",i[4])
print("*"*50)
#Displaying the structure of the table
def display_structure():
print("STRUCTURE OF THE TABLE")
print("="*40)
print()
cur.execute("describe student")
print("Field\t Type \t\t Null \t Key \t Default")
print("*"*50)
for i in cur:
print(i[0],"\t",i[1],"\t",i[2],"\t",i[3])
print("*"*50)
c=1
while c:
print("1. Insert rows into the table")
print("2. Display the contents of the table")
print("3. Display the structure of the table")
print("0. To Exit")
c=int(input("Enter your choice: "))

53
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

if c==1:
insert()
elif c==2:
display()
elif c==3:
display_structure()
elif c==0:
break
else:
print("Wrong choice. Connection closed.....")
cur.close()
con.close()

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

54
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

17. CONNECTING MYSQL WITH PYTHON – 2


AIM:
Create a python application to
i) To alter structure of table with additional attribute Marks to the
table student
ii) To update data in the Marks field for students of class 11 C to 90
iii) To sort the table in descending order of marks
iv) To display content of the table.
Source code:
'''Create a python application to
i) To alter structure of table with additional attribute Marks to the
table student
ii) To update data in the Marks field for students of class 12 D to
92,12 C to 90 , 12 A to 80\
iii) To sort the table in descending order of marks
iv) To display content of the table.'''
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passw
d="",charset="utf8")
cur=con.cursor()
#Make Database Active
cur.execute("use school")
#Alter Table

55
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

cur.execute("desc student")
for i in cur:
print(i)
print( "like to alter table Y/N")
ch=input()
if ch=="Y" or ch=="y":
cur.execute("Alter table student add column marks
decimal(6,2)")
c=1
else:
c=0
#update data in the rows

cur.execute("select * from student")


j= cur.fetchall()
print(j)

while c:
cl=input("Enter Class")
d=input("Enter division")
ma = int(input("Enter Marks"))
cur.execute("update student set marks = {} where class = '{}' and
section ='{}' ".format(ma,cl,d))
56
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print("To stop Enter 0, To continue Enter 1")


c=int(input())
con.commit()
# Print Table i descending order
print("Table in descending order of Marks")
cur.execute("select * from student order by marks desc")
for i in cur:
print(i)
print("*"*10)
# Display the table
cur.execute(" Select * from student")
for i in cur:
print("Roll no :",i[0])
print("Name :",i[1])
print("Telephone No:",i[2])
print("Marks :",i[3])
print("Class :",i[4])
print("Division :", i[5])
cur.close()
con.close()
OUTPUT:
RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS
VERIFIED SUCCESSFULLY
57
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

18. CONNECTIVITY: DELETING


AIM:
Create python application:
To delete a row from a table
To delete all rows from a table
To drop the table
SOURCE CODE:
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="",charset="utf8")
cur=con.cursor()
#Make Database Active
cur.execute("use school")
# delete a row
x= int(input(“roll no to delete”))
cur.execute(“delete from student where rollno={}”.format(x))
con.commit()
# delete all rows
cur.execute(“delete from student)
con.commit()
# drop table

cur.execute(“drop table if exists student”)


cur.close()
con.close()
OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS VERIFIED


SUCCESSFULLY

58
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

19. CONNECTIVITY: USING GROUP BY CLAUSE,JOIN


AIM:
20 i) Create database school
Create database if not exists school;

ii) Create tables students and sports.


Use school;
Create table students( admno int(5), Name varchar(20),class
int(2), Sec char(1) ,address varchar(30), phone varchar(10));
Create table sports ( Admno int(5), game varchar(15), coachname
varchar(20), Grade char(1));

iii) Insert data into tables.


Insert into students values(1211,”Meena”,12,’D’,”A-26,Tilak
road, New Delhi”,”9898245678”);
Insert into students values(1212,”vani”,10,’D’,
NULL,”6565456789”);
Insert into students values(1214,”Karish”,10,’B’,”AB-234,MG
road, New Delhi”,”8984567890”);
Insert into students values(1215,”Suraj”,11,’C’,” Zw12, Shastri
Marg ,Delhi”,”7874345677”);
Insert into sports values(1215,’Cricket’,”Mr. Raj”,’A’);
Insert into sports values(1213,’Volleyball’ “Ms. chandha”,’B’);

59
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Insert into sports values(1211,’volleyball’ “Mr. Govindhan”,’A’);


Table: STUDENTS
ADM NAME CLA SEC ADDRESS PHONE
NO SS
1211 Meena 12 D A-26, Tilak Road, 9898245678
New Delhi
1212 Vani 10 D NULL 6565456789
1214 Karish 10 B AB-234, MG Road, 8984567890
New Delhi
1215 Suraj 11 C ZW12, Shastri Marg, 7874345677
Delhi
TABLE: SPORTS
ADMNO GAME COACHNAME GRADE
1215 Cricket Mr.Rai A
1213 Volleyball Ms. Chadha B
1211 Volleyball Mr. Govardhan A
1212 Basket Ball Mr. Tiwari B
Create a Python application to
i) Display the number of coaches for each game
ii) Display the admno, name, class, section, game and coach name
of the students
iii) Display the number of students in each class
iv) Display the names of coaches who have “ball” in their games

60
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

v) Display the details of the students whose address is NULL.

SOURCE CODE:
'''
Create database school
Create tables students and sports.
Insert data into tables.
Create a Python application to
i) Display the number of coaches for each game
ii) Display the admno, name, class, section, game and coach name
of the students
iii) Display the number of students in each class
iv) Display the names of coaches who have “ball” in their games
v) Display the details of the students whose address is NULL'''

import mysql.connector as sql


con=sql.connect(host="localhost",
user="root",passwd="",charset="utf8")
cur=con.cursor()
cur.execute("use school")
# Display the number of coaches for each game
cur. execute(" select game, count(game) from sports group by
game")

61
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

print(" No of coached for each game")


for i in cur:
print(i[0] ,"\t",i[1])
#Display the admno, name, class, section, game and coach name of
the students
cur. execute(" select s.admno,name,class,Sec, game, coachname
from students s,\
sports s1 where s.admno=s1.admno")
print(" Details of sport coaches")
for i in cur:
print(i[0] ,"\t",i[1],"\t",i[2],"\t",i[3],"\t",i[4],"\t",i[5])
#Display the number of students in each class
cur.execute("select class,count(*) from students group by class")
print(" No of students in each class")
for i in cur:
print(i[0] ,"\t",i[1])

#Display the names of coaches who have “ball” in their games


cur.execute("select coachname, game from sports where game like
'%ball%' ")
print(" Coach name who have ball in their games")
for i in cur:
print(i[0] ,"\t",i[1])

62
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

#Display the details of the students whose address is NULL


print("Details of the students whose address is NULL")
cur.execute("select * from students where address is NULL")
for i in cur:
print(i)
cur.close()
con.close()

OUTPUT:

RESULT: THUS THE ABOVE PROGRAM IS EXECUTED AND OUTPUT IS


VERIFIED SUCCESSFULLY

63
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

20. SQL COMMANDS -1

(i) Display the Mobile company, Mobile name & price in descending

order of their manufacturing date.

Ans. SELECT M_Compnay, M_Name, M_Price FROM MobileMaster

ORDER BY M_Mf_Date DESC;

(ii) List the details of mobile whose name starts with “S”.

Ans. SELECT * FROM MobileMaster

WHERE M_Name LIKE “S%‟;

(iii) Display the Mobile supplier & quantity of all mobiles

except “MB003‟.

64
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Ans.SELECT M_Supplier, M_Qty FROM MobileStock

WHERE M_Id <>”MB003”;

(iv) To display the name of mobile company having price between 3000 &

5000.

Ans. SELECT M_Company FROM MobileMaster

WHERE M_Price BETWEEN 3000 AND 5000;

**Find Output of following queries

(v) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;

MB004 450

MB003 400

MB003 300

MB003 200

65
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

(vi) SELECT MAX(M_Mf_Date), MIN(M_Mf_Date) FROM MobileMaster;

2017-11-20 2010-08-21

(vii) SELECT M1.M_Id, M1.M_Name, M2.M_Qty, M2.M_Supplier

FROM MobileMaster M1, MobileStock M2 WHERE M1.M_Id=M2.M_Id

AND M2.M_Qty>=300;

MB004 Unite3 450 New_Vision

MB001 Galaxy 300 Classic Mobile Store

viii) SELECT AVG(M_Price) FROM MobileMaster;

5450

66
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

21. SQL COMMANDS – 2

i. Display the Trainer Name, City & Salary in descending order of

theirHiredate.

Ans. SELECT TNAME, CITY, SALARY FROM TRAINER

ORDER BY HIREDATE;

ii. To display the TNAME and CITY of Trainer who joined the Institute in

the month of December 2001.

Ans. SELECT TNAME, CITY FROM TRAINER

WHERE HIREDATE BETWEEN ‘2001-12-01’

AND ‘2001-12-31’;

67
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

iii. To display TNAME, HIREDATE, CNAME, STARTDATE from

tables TRAINER and COURSE of all those courses whose FEES is less than

or equal to 10000.

Ans. SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE

WHERE TRAINER.TID=COURSE.TID AND FEES<=10000;

iv. To display number of Trainers from each city.

Ans. SELECT CITY, COUNT(*) FROM TRAINER

GROUP BY CITY;

**Find Output of following queries

v. SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’,

‘MUMBAI’);

Ans.

103 DEEPTI

106 MANIPRABHA

vi. SELECT DISTINCT TID FROM COURSE;

Ans.

101

103

102

104

68
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

105

vii. SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID

HAVING COUNT(*)>1;

Ans.

101 2 12000

viii. SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE<

‘2018-09-15’;

Ans.

4 65000

69
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

22 – SQL COMMANDS - 3

i) To display details of those Faculties whose salary is greater than 12000.

Ans: Select * from faculty

where salary > 12000;

ii) To display the details of courses whose fees is in the range of 15000 to

50000 (both values included).

Ans: Select * from Courses

where fees between 15000 and 50000;

iii ) To increase the fees of all courses by 500 of “System Design” Course.

Ans: Update courses set fees = fees + 500

where Cname = “System Design”;

70
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

(iv) To display details of those courses which are taught by ‘Sulekha’ in

descending order of courses.

Ans: Select * from faculty,courses

where faculty.f_id = course.f_id and fac.fname = 'Sulekha'

order by cname desc;

**Find output of following

v) Select COUNT(DISTINCT F_ID) from COURSES;

Ans: 4

vi) Select MIN(Salary) from FACULTY,COURSES where COURSES.F_ID =

FACULTY.F_ID;

Ans: 6000

vii) Select sum(fees) from COURSES where F_ID = 102;

Ans: 60000

vii) Select avg(fees) from COURSES;

Ans: 17500

71
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

23 – SQL COMMANDS -4

i. To display all the details of those watches whose name ends with ‘Time’

Ans select * from watches

where watch_name like ‘%Time’;

ii. To display watch’s name and price of those watches which have price

range in between 5000-15000.

Ans. select watch_name, price from watches

where price between 5000 and 15000;

iii. To display total quantity in store of Unisex type watches.

Ans. select sum(qty_store) from watches where type like ’Unisex’;

72
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

iv. To display watch name and their quantity sold in first quarter.

Ans. select watch_name,qty_sold from watches w,sale s

where w.watchid=s.watchid and quarter=1;

v. select max(price), min(qty_store) from watches;

Ans. 25000 100

vi. select quarter, sum(qty_sold) from sale group by quarter;

1 15

2 30

3 45

4 15

vii. select watch_name,price,type from watches w, sales s where

w.watchid!=s.watchid;

HighFashion 7000 Unisex

viii. select watch_name, qty_store, sum(qty_sold), qty_store-

sum(qty_sold) “Stock” from watches w, sale s where w.watchid=s.watchid

group by s.watchid;

HighTime 100 25 75

LifeTime 150 40 110

Wave 200 30 170

Golden Time 100 10 90

73
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

24. SQL COMMANDS - 5

(i) To display the records from table student in alphabetical order as per

the name of the student.

Ans. Select * from student

order by name;

(ii ) To display Class, Dob and City whose marks is between 450 and 551.

Ans. Select class, dob, city from student

where marks between 450 and 551;

(iii) To display Name, Class and total number of students who have

secured more than 450 marks, class wise

Ans. Select name,class, count(*) from student

group by class

having marks> 450;

(iv) To increase marks of all students by 20 whose class is “XII


74
PRACTICAL PROGRAMS WITH SOLUTION
COMPUTER SCIENCE - XII

Ans. Update student

set marks=marks+20

where class=’XII’;

**Find output of the following queries.

(v) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY HAVING

COUNT(*)>1;

2 Mumbai

2 Delhi

2 Moscow

(vi ) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;

08-12-1995 07-05-1993

(iii) SELECT NAME,GENDER FROM STUDENT WHERE CITY=’Delhi’;

Sanal F

Store M

-----xxx-----

75

You might also like