678676286 Class 12 Computer Science Practical File 2023 24 (1)
678676286 Class 12 Computer Science Practical File 2023 24 (1)
PRACTICAL FILE
Student Name
Grade :
Roll No. :
Certificate
student of Class 12-th B has successfully completed their computer Science (New-
Principal
Page 2 of 45
PRACTICAL FILE- COMPUTER SCIENCE (083) LIST OF
PRACTICALS (2023-24)
CLASS-XII
1 Write a program to check a number whether Submission Teacher’s
Date Sign
it is palindrome or not.
Page 3 of 45
12 Create a binary file with roll number, name
and marks. Input a roll number and update
details. Create a binary file with roll number,
name and marks. Input a roll number and
update details.
13 # Write a program to perform read and write
operation onto a student.csv file having fields
as roll number, name, stream and
percentage.
14 Write a program to create a library in python
and import it in a program.
15 Take a sample of ten phishing e-mails (or any
text file) and find the most commonly
occurring word(s).
16 Write a python program to implement a stack
using a list data-structure.
17 Write a program to implement a queue using
a list data structure.
18 SQL Queries
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.
Page 4 of 45
Practical No-1
# Write a program to check a number whether it is palindrome or not.
SOURCE CODE:
num=int(input("Enter a number : ")) n=num
res=0
while num>0:
rem=num%10 res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
Output -
Page 5 of 45
Practical No-2
# Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a character of a
value\n"))
if choice==1:
else:
var=False
Page 6 of 45
# Program to make simple calculator
while True:
choice = input("Select operation: 1.Add 2.Subtract 3.Multiply 4.Divide\nEnter choice(1/2/3/4): ")
if choice in operations:
num1, num2 = float(input("Enter first number: ")), float(input("Enter second number: "))
print(f"{num1} {['+', '-', '*', '/'][int(choice)-1]} {num2} = {operations[choice](num1, num2)}")
else:
print("Invalid Input")
Page 7 of 45
Practical No-4
# Example of Global and Local variables in function
x = "global "
def display():
global x
y = "local"
x=x*2
print(x)
print(y)
display()
Output -
Page 8 of 45
Practical No-5
# Python program to count the number of vowels, consonants, digits and
special characters in a string
str = input("Enter the string: ").lower()
vowels = digits = consonants = spaces = symbols = 0
for char in str:
if char in 'aeiou':
vowels += 1
elif char.isalpha():
consonants += 1
elif char.isdigit():
digits += 1
elif char == ' ':
spaces += 1
else:
symbols += 1
Page 9 of 45
Practical No-6
# Python Program to find Palindrome Number
n = int(input("Enter the number: "))
original = n
reversed_number = 0
while n > 0:
reversed_number = reversed_number * 10 + n % 10
n = n // 10
if original == reversed_number:
print(original, "is a palindrome number")
else:
print(original, "is not a palindrome number")
OUTPUT :
Page 10 of 45
Practical No-7
# Generating a List of numbers Using For Loop
import random
randomlist = []
for i in
range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
Output -
Practical No-8
# Write a program to read a text file line by line and display each word
separated by '#'.
Page 11 of 45
Practical No-8
# Write a program to read a text file line by line and display each word
separated by '#'.
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
Output -
Text in file:
O
utput in python shell
Page 12 of 45
Pra
ctic
al
No-
9
# Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters and other than character and digit in the file.
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
Page 13 of 45
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
Page 14 of 45
print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-
count_vow) print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
Practical No-10
# Remove all the lines that contain the character `a' in a file and write it to
another file
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
Page 15 of 45
Page 16 of 45
Practical No-10
# Write a Python code to find the size of the file in bytes, the number of lines,
number of words and no. of character.
import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")
# A flag that signals the location outside the word.
pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'
print("Size of File
is",filesize,'bytes') print("Lines:",
lines) print("Words:", words)
print("Letters:", letters)
Page 17 of 45
Practical No-11
# Create a binary file with the name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
import pickle
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname} pickle.dump(srecord,Myfile)
def Readrecord():
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile: while True:
try:
rec=pickle.load(Myfile) if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
Page 18 of 45
except EOFError:
print("Try Again...................")
break
def main():
while True:
main()
Page 19 of 45
Page 20 of 45
Practical No-12
# Create a binary file with roll number, name and marks. Input a roll number
and update details. Create a binary file with roll number, name and marks.
Input a roll number and update details.
def Writerecord(sroll,sname,sperc,sremark): with open
('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc, "SREMARKS":sremark}
pickle.dump(srecord,Myfile) def
Readrecord():
with open ('StudentRecord.dat','rb') as Myfile: print("\n-------DISPALY
STUDENTS DETAILS-----------------------------------------------------------")
print("\nRoll No.",' ','Name','\t',end='') print('Percetage',' ','Remarks')
while True: try:
rec=pickle.load(Myfile)
def Input():
def Modify(roll):
if newRecord[i]['SROLL']==roll: name=input("Enter
Name: ") perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ") newRecord[i]
['SNAME']=name newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark found =1
else:
found=0 if
found==0:
print("Record not found")
break
main()
Page 22 of 45
Page 23 of 45
Practical No-13
# Write a program to perform read and write operation onto a student.csv file
having fields as roll number, name, stream and percentage.
import csv
choice='y'
Page 24 of 45
Practical No-14
# Write a program to create a library in python and import it in a program.
#Let's create a package named Mypackage, using the following steps:
#• Create a new folder named NewApp in D drive (D:\NewApp)
#• Inside NewApp, create a subfolder with the name 'Mypackage'.
#• Create an empty init .py file in the Mypackage folder
#• Create modules Area.py and Calculator.py in Mypackage folder with
following code
# Area.py Module
import math
def rectangle(s1,s2):
area = s1*s2 return
area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
Page 25 of 45
return area
# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2): r
= n1 - n2
return r
def mult(n1,n2): m
= n1*n1 return
m
def div(n1,n2):
d=n1/n2
return d
# main() function
Page 26 of 45
print("The Area of Rectangle is:",area)
Page 27 of 45
Practical No-15
# Take a sample of ten phishing e-mails (or any text file) and find the most
commonly occurring word(s).
def Read_Email_File(): import
collections
fin = open('email.txt','r') a=
fin.read()
d={ }
L=a.lower().split() for
word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
key=k
if key not in d:
count=L.count(key)
d[key]=count
n = int(input("How many most common words to print: ")) print("\nOK. The {}
most common words are as follows\n".format(n))
word_counter = collections.Counter(d)
Page 28 of 45
for word, count in word_counter.most_common(n):
print(word, ": ", count)
fin.close()
Page 29 of 45
Practical No-16
# Write a python program to implement a stack using a list data-structure.
def isempty(stk): if
stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk): return
"underflow"
else:
item=stk.pop() if
len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
Page 30 of 45
def display(stk): if
isempty(stk):
print('stack is empty') else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
#Driver Code
2. pop
3.peek
4.display
5.exit''')
else:
item=peek(stk)
Page 31 of 45
if item=="underflow": print('stack is underflow')
else:
print('top most item is:',item) elif choice==4:
display(stk) elif choice==5:
break else:
print('invalid') exit()
main()
Page 32 of 45
Page 33 of 45
Practical No-17
# Write a program to implement a queue using a list data structure.
return 0
else:
val = qLst.pop(0) if
len(qLst)==0:
front=rear=None
return val
Page 34 of 45
# Function to Display top element of Queue def
Peek(qLst):
if isEmpty(qLst): return
"UnderFlow"
else:
front=0
return qLst[front]
else:
tp = len(qLst)-1
print("[FRONT]",end=' ')
front = 0
i = front
rear = len(qLst)-1
while(i<=rear):
print(qLst[i],'<-',end=' ') i
+= 1
print()
# Driver function
def main():
qList = []
front = rear = 0 while
Page 35 of 45
True:
print()
val = Dqueue(qList)
if val == "UnderFlow":
elif choice==3:
val = Peek(qList)
Page 36 of 45
elif choice==4: Display(qList)
elif choice==0: print("Good
Luck..............................")
break
main()
OUTPUT:
Page 37 of 45
Practical No-18
SQL
Create a table EMPLOYEE with constraints
SOLUTION
Page 38 of 45
Query OK, 1 row affected (0.11 sec)
Note: Insert more rows as per above insert command.
Page 39 of 45
Change the data-type and size of an existing column.
SOLUTION
ALTER TABLE EMPLOYEE MODIFY city char(30);
Write SQL queries using SELECT, FROM, WHERE clause based on
EMPLOYEE table.
1. List the name of female employees in EMPLOYEE table.
Solution:-
SELECT Ename FROM EMPLOYEE WHERE sex=’F’;
Page 40 of 45
4. Display the name of those employees whose department is marketing or
RND.
Solution:-
SELECT Ename FROM EMPLOYEE WHERE Dept=’marketing’ OR Dept=’RND’
Page 41 of 45
Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,
GROUP BY, HAVING
A. Display the name of departments. Each department should be
displayed once.
SOLUTION
SELECT DISTINCT(Dept) FROM EMPLOYEE;
B. Find the name and salary of those employees whose salary is
between 35000 and 40000.
SOLUTION
SELECT Ename, salary FROM EMPLOYEE WHERE salary BETWEEN 35000 and
40000;
C. Find the name of those employees who live in guwahati, surat or jaipur city.
SOLUTION
SELECT Ename, city FROM EMPLOYEE WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
D. Display the name of those employees whose name starts with
‘M’. SOLUTION
SELECT Ename FROM EMPLOYEE WHERE Ename LIKE ‘M%’;
E. List the name of employees not assigned to any department.
SOLUTION
SELECT Ename FROM EMPLOYEE WHERE Dept IS NULL;
F. Display the list of employees in descending order of employee code.
SOLUTION
SELECT * FROM EMPLOYEE ORDER BY ecode DESC;
Page 42 of 45
G. Find the average salary at each department.
SOLUTION
SELECT Dept, avg(salary) FROM EMPLOYEE group by Dept;
H. Find maximum salary of each department and display the name of
that department which has maximum salary more than 39000.
SOLUTION
SELECT Dept, max(salary) FROM EMPLOYEE group by Dept HAVING
max(salary)>39000;
Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
a. Find the average salary of the employees in employee table.
Solution:-
SELECT avg(salary) FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
Solution:-
SELECT Ename, min(salary) FROM EMPLOYEE WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE table.
Solution:-
SELECT Ename, max(salary) FROM EMPLOYEE WHERE sex=’M’;
d. Find the total salary of those employees who work in Guwahati city.
Solution:-
SELECT sum(salary) FROM EMPLOYEE WHERE city=’Guwahati’;
e. Find the number of tuples in the EMPLOYEE relation.
Solution:- SELECT count(*) FROM EMPLOYEE
Page 43 of 45
Practical No-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.
A. CREATE A
TABLE SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
sname varchar(30), gender char(1), DOB date, stream varchar(15), marks
float(4,2))")
B. INSERT THE
DATA SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)",
(1245, 'Arush', 'M', '2003-10-04', 'science', 67.34))
demodb.commit( )
C. FETCH THE
DATA SOLUTION
import mysql.connector
Page 44 of 45
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("select * from student")
for i in democursor:
print(i)
D. UPDATE THE
RECORD SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE
DATA SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit()
Page 45 of 45