12 Cs Practical File 2024-25
12 Cs Practical File 2024-25
ROLL NO. :
REG. NO. :
SESSION : 2024 – 25
Submit To :
Falguni Mondal
TGT Computer Science
Certificate
This is to certify that Ankan Chattopadhyay , a student of
Class 12, of Gitanjali Public School, Daikota, Sainthia,
Birbhum has successfully completed and submitted the
practical file of Computer Science (083) as per the guidelines
provided by CBSE in the prescribed curriculum for academic
year 2024-25 for accomplishment of Senior School
Certificate Examination - 2025.
The practical file has been evaluated and found correct in
accordance with the guidelines provided by the board- for
Academic year 2024-25. The work has been completed and
presented in a satisfactory manner.
No. of practical certified are: 24
Page |2
Acknowledgement
I wish to express my heartfelt thanks to
everyone involved in preparing my class
12 computer science practical file.
Page |3
Additionally, I must extend my gratitude
to my parents, whose unwavering support
was evident at every step.
Page |4
Index
Sno. Assignment Page Date Sign.
Part A – Python Programs
Python Revision Tour
1 List Menu Driven Program 5 07-04-2024
2 Dictionary Menu Driven Program 6 22-04-2024
Working with Functions
3 Using a function to display prime numbers between m & n. 7 13-06-2024
Using a function calculate interest using various
4 8 18-06-2024
arguments.
Using a function find a largest element in a list. Pass list
5 9 26-06-2024
object as argument.
Using a function count the number of vowels in passed
6 10 04-07-2024
string.
Exception Handling
Take two integers and perform addition of two numbers
7 11 15-07-2024
handle exception when non-integers entered by user
Find the square root of a positive number, raise a custom
8 12 18-07-2024
exception when user enters a negative number
File handling
9 Find and replace a word in a text file 13 23-07-2024
Menu driven program for binary file to insert, update,
10 14 06-08-2024
delete and display records
Menu driven program for csv file to insert, update and
11 19 23-08-2024
delete records
12 Search record in binary file using user defined condition 21 28-08-2024
13 Search record in csv file using user defined condition 22 29-08-2024
Data Structure – Stack
14 Menu driven program for stack operations 26 07-09-2024
Searching data from dictionary and transfer keys into
15 29 10-09-2024
stack then performing push operations
Part B – MySQL Queries
16 Set 1 – Based on Database Basic Commands 31 01-10-2024
17 Set 2 – Based on DDL Commands 32 04-10-2024
18 Set 3 – Select Queries including order by 35 09-10-2024
19 Set 4 – Group by, having and Aggregate Functions 37 14-10-2024
20 Set 5 – Join Queries 39 17-10-2024
Part C – Python Database Connectivity
21 Insert record in a database table 41 12-11-2024
22 Update a record in a database table 42 14-11-2024
23 Delete a record in a database table 43 18-11-2024
24 Display records using queries from database table 44 20-11-2024
Page |5
Part A – Python Programs
Python Revision Tour
1. Write a program to find the sum and average of list in python.
Code:
#Creating list with user defined list
l=[] #Declare an empty list
while True:
n=int(input("Enter no. to add into the list:"))
l.append(n)
ch=input("Press 'X' to stop:")
if ch in 'xX':
break
s=0
n=len(l)
for i in l:
s+=i
avg=s/n
print("The list is:",l)
print("Sum is:",s)
print(f"Average is:{avg:.2f}")
Output:
Page |6
2. Write a program to remove duplicates from the dictionary
Code:
#Creating empty dictionary
d={}
#Ask user to enter number of key:value pairs
n=int(input("Enter no. of elements:"))
for i in range(n):
k=input("Enter Key:")
v=input("Enter value:")
d[k]=v
#Declare empty dictionary to store unique key-value pairs
uni_dict={}
#Traverse dictionary to remove duplicates and store into unique
dictionary
for k in d:
val=d[k]
if val not in uni_dict.values():
uni_dict[k]=val
#Output
print("Dictionary After removing duplicates:",uni_dict)
Output:
Page |7
Working with functions
3. Write a program to define a function to accept two integers m and
n respectively as argument and display prime numbers between them.
Code:
# Function to check and display prime in the range
def prime_m_to_n(m,n):
for i in range(m, n + 1):
# all prime numbers are greater than 1
if i > 1:
for j in range(2, i):
if (i % j) == 0:
break
else:
print(i, end=' ')
# Taking input for m and n
m = int(input("Enter the value of m: "))
n = int(input("Enter the value of n: "))
# Calling the function
prime_m_to_n(m, n)
Output:
Page |8
4. Write a program to compute interest based on different arguments
given in the function.
Code:
# Function to calculate interest
def compute_int(pri, r=5, t=1, comp=False):
if comp:
amt = pri * (1 + r / 100) ** t
i = amt - pri
else:
i = (pri * r * t) / 100
return i
# Testing the function with various argument combinations
p=int(input("Enter Principle:"))
r=float(input("Enter custom rate:"))
t=float(input("Enter time:"))
# Case 1: Only principal provided, default rate and time
print("Interest (Simple, default):", compute_int(1000))
# Case 2: Principal and rate provided, default time
print("Interest (Simple, custom rate):", compute_int(p, r))
# Case 3: Principal, rate, and time provided
print("Interest (Simple, custom rate and time):", compute_int(p,
r,t))
# Case 4: Compound interest, with custom rate and time
print(f"Interest (Compound, custom rate and time):
{compute_int(p,r, t,True):.2f}")
Output:
Page |9
5. Write a program to largest element in a list using a function. Pass list
object as argument.
Code:
# Function to find the largest element in a list
def find_largest(l):
if not l: # Check the list is empty or not
return None # Return None if the list is empty
large = l[0] # Assume the first element is the large
for i in l:
# Check if other element than first is large
if i > large:
# Update the largest if a bigger number is
found
large = i
return large
# Taking input as a list
lst = eval(input("Enter list as input:"))
# Calling the function and printing the result
large_ele = find_largest(lst)
if large_ele is not None:
print(f"The largest element in the list is: {large_ele}")
else:
print("The list is empty.")
Output:
P a g e | 10
6. Write a program to count the number of vowels in passed string to the
function.
Code:
def count_vowels(s):
# Define a set of vowels (both lowercase and uppercase)
vowels = "aeiouAEIOU"
# Initialize a counter variable
count = 0
# Loop through each character in the string
for char in s:
if char in vowels:
count += 1
return count
# Passing string and calling function
input_string = input("Enter a string: ")
print("Number of vowels:", count_vowels(input_string))
Output:
P a g e | 11
Exception Handling
7. Write a program to take two positive integers and perform addition
among them handle exception when negative integers entered by user.
Code:
def add(n1,n2): # Define a function to add and return
error
if n1<0 or n2<0: #Checking for error
raise ValueError("Negative number entered!")
else:
return n1 + n2 #Performing Addition
try: #Handling exception using try
no1 = int(input("Enter number1: "))
no2 = int(input("Enter number2: "))
print(f"The result is: {add(no1,no2)}")
except ValueError as e:
print(f"Error: {e}")
Output:
P a g e | 12
8. Write a program to find the square root of a positive number, raise a
custom exception when user enters a non-integer number.
Code:
import math # Importing math module
def find_square_root(): #Define a function
try: # Handling exception
# Input a number
num = float(input("Enter a number: "))
# Condition to check positive integer
if num <= 0 or num % 1 != 0:
raise ValueError("Input must be a positive
integer")
# Calculating Square root
square_root = math.sqrt(num)
# Output
print(f"The square root of {num} is {square_root}")
#Generating Error message
except ValueError as e:
print(f"Custom Error: {e}")
find_square_root()
Output:
P a g e | 13
File Handling
9. Write a program to replace entered word from a text file india.txt.
Code:
def replace_word(f, old_word, new_word):
with open(f, 'r') as file: # Open a file to read
dt = file.read() # Store data read from file in dt
object
if old_word not in dt: # Checking the presence of old
word
print(f"The word '{old_word}' was not found in the
file.")
return
new_dt = dt.replace(old_word, new_word) # Replace old
word
with open(f, 'w') as file: # Writing new data in the file
file.write(new_dt)
print(f"The word '{old_word}' has been replaced with
'{new_word}' successfully.")
print(new_dt)
f = 'india.txt' # Main Code
old_word = input("Enter the word to be replaced: ")
new_word = input("Enter the new word: ")
replace_word(f, old_word, new_word)
Output:
P a g e | 14
P a g e | 15
10. Write a menu driven program to store and manipulate data in binary
file to insert, update, delete and display records. The data has following
structure:
Data Represents Patient Information
Dictionary {‘P_ID’:101,’P_Name’:’Shiv’,’Charges’:25000}
File Name patient.dat
Menu:
1. Add Patient
2. Display Patient
3. Search Patient
4. Update Patient
5. Delete Patient
6. Exit
Code:
import pickle # import module to handle binary files data
flag = False
while True:
print('''
1. Add Patient
2. Display Patient
3. Search Patient
4. Update Patient
5. Delete Patient
6. Exit
''')
ch = int(input('Enter your choice:'))
if ch == 1:
add_pat()
elif ch == 2:
P a g e | 18
display_pat()
elif ch == 3:
pn = input('Enter a patient name to search:')
search_pat(pn)
elif ch == 4:
update_pat()
elif ch == 5:
deleteRec()
elif ch==6:
print("Bye Bye, Thank you for Interactions")
break
else:
print("Invalid Choice")
Output:
Main Menu
Add Patient
P a g e | 19
Display Patient
Search Patient
Update Patient
Delete Patient
Exit
P a g e | 20
11. Create a CSV file by entering user-id and password, read and search the
password for given userid.
Code:
import csv # importing csv file
users=[] # creating a list to add record
def add_user(): # define function to add user
un=input("Enter Username:")
pwd=input("Enter Password:")
f=open("user.csv","a",newline='')
w=csv.writer(f)
w.writerow([un,pwd])
f.close()
print("User added...")
Output:
Main menu
Add user
Search password
P a g e | 22
12. Write a program to create a binary file candidates.dat which stores the
following information in list as follows:
Structure of Data
Field Data Type
Candidate_id Integer
Candidate_Name String
Designation String
Experience Float
(i)Write a function append() to write data into binary file.
(ii) Write a function display() to display data from binary file for all
candidates whose experience is more than 10.
Code:
import pickle # Module to work with binary files
def append():
with open("Candidates.dat",'ab') as f:
C_id=int(input("Enter Candidate ID: "))
C_nm=input("Enter Candidate name: ")
C_dg=input("Enter Designation: ")
C_ex=float(input("Enter Experience: "))
rec=[C_id,C_nm,C_dg,C_ex]
pickle.dump(rec,f)
def display(): # Display data after reading file contents
with open("Candidates.dat",'rb') as f:
while True:
try:
rec=pickle.load(f)
if rec[-1]>10:
print(rec)
except EOFError:
break
append() # Calling functions
display() # Calling functions
Output:
P a g e | 23
13. Write a program to generate a CSV file named happiness.csv.
Each record of CSV contains these data:
Name of the country String
Population of country Integer
No. people participated in survey Integer
No. of people who are Happy Integer
Write user defined functions to do the following:
(i) Insert records into CSV
(ii) Display records from CSV
(iii)Update records
(iv)Delete record
Code:
import csv # Import a module to work with csv
h=[] # a list object to store records
def header_row(): # A function to create header row, run only
once
f=open("happiness.csv",'w',newline='')
wo=csv.writer(f)
wo.writerow(['Country','Population','Participants', 'Happy
People'])
print("A CSV file with header is created...")
f.close()
P a g e | 24
wo.writerow([country,population,participants,happy])
print("Record inserted...")
Output:
P a g e | 27
Data Structure - Stack
14. Write a menu drive program for stack operations.
Code:
s=[] # An empty list to store stack elements, initially its
empty
top = None # This is top pointer for push and pop operation
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_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])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
P a g e | 28
top = len(stk)-1
return e
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an
element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
P a g e | 29
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
main_menu()
Output:
P a g e | 30
15. Write a program to Push an item into stack where a dictionary contains
the details of stationary items as follows:
stn = {“Shirt”:700,”T-Shirt”:750, ”Jeans”:1150,”Trouser”:400}
(a) Write a function to push an element into stack for those items names
whose price is more than 450. Also display the count of elements pushed
into the stack.
(b) Write a function to pop an element to remove the element and
display appropriate message when the stack is empty.
Code:
stn = {}
while True:
item=input("Enter itemname:")
price=float(input("Enter Price:"))
stn[item]=price
ch=input("Press X to stop:")
if ch in 'xX':
break
def Push(stk,ele):
stk.append(ele)
return stk
def Pop(stk):
if stk==[]:
return "underflow"
else:
return stk.pop()
stak=[]
c=0
for i in stn:
if stn[i]>450:
Push(stak,i)
c+=1
print("Total Stack elements are:",c)
P a g e | 31
while True:
if stak!=[]:
print(Pop(stak))
else:
print("Stack is Empty")
break
Output:
P a g e | 32
Part B – MySQL Queries
Simple Queries in SQL
16. Based on Database Basic Commands write SQL for following:
P a g e | 33
17. Based on DDL Commands consider the following MOVIES table and
write the SQL commands based on it.
Movie_ Producti Business
MovieName Type ReleaseDate
ID onCost Cost
M001 Dahek Action 2022/01/26 1245000 1300000
M002 Attack Action 2022/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2022/02/01 250000 300000
M004 Badhai Do Drama 2022/02/04 720000 68000
M005 Shabaash Mithu Biography 2022/02/04 1000000 800000
M006 Gehraiyaan Romance 2022/02/11 150000 120000
M007 Border 2 Action null 3211400 2500000
1. Create above table, assign Movie_ID as a primary key and insert records as
above.
P a g e | 34
2. Show the structure of table
mysql> desc movies;
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| Movie_ID | varchar(5) | NO | PRI | NULL | |
| MovieName | varchar(50) | YES | | NULL | |
| Type | varchar(20) | YES | | NULL | |
| ReleaseDate | date | YES | | NULL | |
| ProductionCost | int(11) | YES | | NULL | |
| BusinessCost | int(11) | YES | | NULL | |
+----------------+-------------+------+-----+---------+-------+
6 rows in set (0.023 sec)
3. Add a column named collection with decimal data type with structure 12, 2
P a g e | 35
5. Rename a column MovieName to MName
mysql> alter table movies change column moviename mname varchar(50);
Query OK, 0 rows affected (0.010 sec)
Records: 0 Duplicates: 0 Warnings: 0
P a g e | 36
18. Select queries including order by based on the previous table.
1. Display the movie name, type, releasedate and total cost of all movies
3. Display movie name, types and releasedate of all movies released in the
month of February, 2022
P a g e | 37
4. Display the details of movies whose name ends with letter k.
6. Display the movie name type release date and production cost in the
descending order of production cost.
P a g e | 38
19. Applying Group by, having and aggregate functions on previous table.
P a g e | 39
5. Display the average business cost of movies for each type.
6. Display the type and number of movies for each type where movie type is
more than two.
mysql> select type, count(*) from movies group by type having count(*)>2;
+--------+----------+
| type | count(*) |
+--------+----------+
| Action | 3 |
+--------+----------+
1 row in set (0.001 sec)
P a g e | 40
20. Join Queries – Create two tables as follows and write given queries
below:
Table: artist
artist_id artist_name label_owner
101 Vishal Shekhar Sony Music
120 Vishal Mishra Zee Music
125 Udit Narayan T-Series
Table: song
song_id artist_id song_name
1111 101 Jhume Jo Pathan
1112 120 Khubsoorat
1113 125 Papa Kehte hai
1114 101 Swag Se Swagat
1115 120 Narazagi
1116 125 Phir Bhi Dil Hai Hindustani
1117 125 Mei Nikal Gaddi Leke
1118 120 Pehle Bhi Mein
1119 101 Jai Jai Shiv Shankar
P a g e | 41
2. Display the records of artist and song using equijoin.
3. Display the records of artist and song tables using natural join.
5. Display artist name, song name from artist and song which song starts with ‘p’.
P a g e | 42
Part C – Python & MySQL Connectivity Programs
Interface Python with MySQL
21. Write a program to connect with mysql database and insert a record
into database.
database name : practical_2025, username: root, password: root, table: artist
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',databas
e='practical_2025')
cur=cn.cursor()
aid=int(input("Enter Artist ID:"))
aname=input("Enter Artist Name:")
lbl=input("Enter Label:")
cur.execute("insert into artist
values({},'{}','{}')".format(aid,aname,lbl))
cn.commit()
print("Record Inserted...")
cn.close()
Output:
P a g e | 43
22. Write a program to connect with mysql database and update a record
into database.
database name : practical_2025, username: root, password: root, table: artist
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',databas
e='practical_2025')
cur=cn.cursor()
aid=int(input("Enter Artist ID:"))
aname=input("Enter Artist Name:")
lbl=input("Enter Label:")
cur.execute("update artist set artist_name='{}',label_owner='{}'
where artist_id={}".format(aname,lbl,aid))
cn.commit()
print("Record Updated...")
cn.close()
Output:
P a g e | 44
23. Write a program to connect with mysql database and delete a record
into database.
database name : practical_2025, username: root, password: root, table: artist
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',databas
e='practical_2025')
cur=cn.cursor()
aid=int(input("Enter Artist ID to delete:"))
cur.execute("delete from artist where artist_id
={}".format(aname,lbl,aid))
cn.commit()
print("Record Deleted...")
cn.close()
Output:
P a g e | 45
24. Write a program to connect with mysql database display record of
particular label under the artist is working.
database name : practical_2025, username: root, password: root, table: artist
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',databas
e ='practical_2025')
cur=cn.cursor()
lbl=input("Enter Label:")
cur.execute("select * from artist where
label_owner='{}'".format(lbl))
dt=cur.fetchall()
for i in dt:
print(i)
cn.close()
Output:
P a g e | 46
Bibliography
1. www.wikipedia.com
2. www.w3schools.com
3. www.geeksforgeeks.org
4. www.stackoverflow.com
5. www.google.com
P a g e | 47