Cbse Computer Science Practical File
Cbse Computer Science Practical File
2
Part A – Python Programs
Chapter 1 - Python Revision Tour
1. Write a program to find the sum and average of list in python.
Code:
#Creating list with user defined list
#Declare an empty list l=[]
while True:
#Input through user
n=int(input("Enter no. to add into the list:"))
#Add element into the end of list
l.append(n)
#Output
print("The list is:",l) print("Sum
is:",s)
print(f"Average is:{avg:.2f}")
3
Output:
4
2. Write a program to remove duplicates from the dictionary Code:
#A program to remove dulicates from the dictionary
for i in range(n):
k=input("Enter Key:")
v=input("Enter value:") d[k]=v
#Output
print("Dictionary After removing duplicates:",uni_dict)
5
Output:
6
Code:
#A program to display prime numbers from a
range # 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=' ')
Output:
7
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:
"""Compound Interest formula: A = P(1 + r/n)^(nt),
where n = 1 for annual compounding""" amt = pri *
(1 + r / 100) ** t i = amt - pri else:
# Simple Interest formula: SI = (P * R * T) / 100
i = (pri * r * t) / 100 return i
8
# Case 3: Principal, rate, and time provided
print("Interest (Simple, custom rate and time):", compute_int(p, r, t))
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):
# Check the list is empty or not
if not l:
# Return None if the list is empty
return None
10
6. Write a program to count the number of vowels in passed string to
the function.
Code:
# A program to count the number of vowels in passed string to the function
def count_vowels(s):
# Define a set of vowels (both lowercase and uppercase)
vowels = "aeiouAEIOU"
11
Chapter 3 – Exception Handling
7. Write a program to take two integers and perform addition of two
numbers handle exception when non-integers entered by user.
Code:
# A program to raise exception when a negative number is entered
# Define a function to add and return error
def add(n1,n2): #Checking for error if
n1<0 or n2<0:
raise ValueError("Negative number entered!")
else:
#Performing Addition
return n1 + n2
Output:
12
8. Write a program to f ind the square root of a positive number, raise
a custom exception when user enters a non-integer number
Code:
# Importing math module
import math
#Define a function
def find_square_root():
# Handling exception
try:
# 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 only")
# 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:
13
Chapter 4 – File Handling
9. Write a program to replace entered word from a text file india.txt.
Code:
# A program to replace entered word from a text file
# Main Code
f = 'india.txt'
old_word = input("Enter the word to be replaced: ")
new_word = input("Enter the new word: ") replace_word(f,
old_word, new_word)
14
Output:
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 module to handle binary files data import
pickle
# A variable to mark as record found to counter loop iteration flag
= False
# Accepting data for Dictionary and dumping into binary file def
add_pat():
# Enter data as Input to add in dictionary
P_ID = int(input('Enter patient_id:')) pname
= input('Enter Patient Name:') charges =
int(input('Enter Charges:'))
16
# Reading and displaying the records def
display_pat():
#Opening a binary file and reading data individually
f = open('patient.dat','rb') while True: try:
rec = pickle.load(f)
print('*'*40)
print('Patient ID:',rec['P_ID'])
print('Name:',rec['P_Name'])
print('charges:',rec['Charges'])
print('*'*40) except EOFError:
break
f.close()
17
flag = True
except EOFError:
break
if flag == False:
print('No Record found...')
f.close()
18
for i in reclst:
pickle.dump(i,f)
f.close()
print("Record modified successfully...")
19
6. Exit
''')
ch = int(input('Enter your choice:'))
if ch == 1:
add_pat()
elif ch == 2:
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
Display Patient
20
Search Patient
Update Patient
Delete Patient
Exit
21
11. Create a CSV file by entering user-id and password, read and
search the password for given userid.
Code:
# importing csv file import
csv
# creating a list to add record users=[]
22
if i[0]==un:
print("Your password for ", i[0], " is:",i[1])
f.close()
Output:
Main Menu
Add User
23
Search Password
Candidate_id Integer
Candidate_Name String
Designation String
Experience Float
24
rec=[C_id,C_nm,C_dg,C_ex]
pickle.dump(rec,f)
25
13. Write a program to generate a CSV file named happiness.csv.
Each record of CSV contains these data:
Name of the country String
26
happy=float(input("Enter no. of people who are happy (In Million):"))
h=[country, population, participants, happy] wo=csv.writer(f)
wo.writerow([country,population,participants,happy])
print("Record inserted...")
i[0]==c:
flg=True
population=float(input("Enter Population (In Billion):"))
participants=float(input("Enter no. of participants (In Million):"))
happy=float(input("Enter no. of people who are happy (In Million):"))
updated_row.append(i)
if flg==True:
with open('happiness.csv','w',newline='') as f:
wo=csv.writer(f)
wo.writerows(updated_row)
print('Record Updated...') else:
print('Record not found...')
27
# Delete Record def delete_rec():
c=input("Enter country to update records:")
deleted_row=[] flg=False with
open('happiness.csv','r') as f:
ro=csv.reader(f)
for i in ro: if
i[0] != c:
flg=True
deleted_row.append(i) if flg==True:
with open('happiness.csv','w',newline='') as f:
wo=csv.writer(f)
wo.writerows(deleted_row)
print('Record Deleted...') else:
print('Record not found...')
28
4. Update Record
5. Delete Record
6. Exit
''')
ch = int(input('Enter your choice:'))
if ch==1:
header_row()
elif ch == 2:
insert_rec()
elif ch == 3:
display_rec()
elif ch == 4:
update_rec()
elif ch == 5:
delete_rec()
elif ch == 6:
29
Create header row (Execute at Once)
Display Record
Update Record
Delete record
30
s=[] # An empty list to store stack elements, initially its
empty top = None # This is top pointer for push and pop
operation 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: print("The element on top
is:",e) elif ch==4: display(s)
elif ch==5: break else:
print("Sorry, You have entered invalid option")
def push(stk,e):
stk.append(e) top = len(stk)-
1 def display(stk): if
check_stack_isEmpty(stk):
print("Stack is Empty") else:
31
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: top =
len(stk)-1 return e def
peek(stk): if
check_stack_isEmpty(stk):
return "UnderFlow" else:
top = len(stk)-1
return stk[top]
main_menu()
32
Output:
Main Menu
Push Element
Pop Element
Peek Element
Display Stack
33
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 850. 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]>35:
Push(stak,i)
c+=1
print("Total Stack elements are:",c)
34
while True:
if stak!=[]:
print(Pop(stak))
else:
print("Stack is Empty")
break
Output:
35
Part B – MySQL Queries
Chapter 11 – Simple Queries in SQL
Set 1 – Based on Database Basic Commands Write
SQL Commands for following:
1. Create a database named practical_2025 Ans.: mysql>
CREATE DATABASE practical_2025;
3. Open a database
Ans.: mysql>use practical_2025
36
Set 2 – Based on DDL Commands
Consider the following MOVIES table and write the SQL commands based on it.
Movie_ID MovieName Type ReleaseDate Produc9onCost BusinessCost
M001 Dahek Ac9on 2022/01/26 1245000 1300000
M002 AHack Ac9on 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
1. Create above table, assign Movie_ID as a primary key and insert records as
34
38
2. Show the structure of table mysql> desc movies;
3. Add a column named collecDon with decimal data type with structure 12, 2
mysql> alter table movies add column collec9on decimal(12,2);
1. Display the movie name, type, releasedate and total cost of all movies
mysql > select mname, type, releasedate, produc9oncost +
businesscost as 'total cost' from movies;
40
2. Display all details of ac9on and thriller movies mysql> select * from
movies where type in ('ac9on','thriller');
41
4. Display the details of mov ies whose name ends with leHer k.
mysql > select * from movies where mname like '%k';
6. Display the movie name type release date and produc9on cost in the
descending order of produc9on cost
mysql> select mname, type, releasedate, produc9oncost from movies order by
produc9oncost desc;
42
Set 4 – Group by, having and aggregate funcDons
1. Display the number of movies for each type
mysql> select type, count(*) from movies group by type;
43
4. Display the date of movies released latest mysql> select
max(releasedate) from movies;
5. Display the average business cost of movies for each type Mysql>
select type, avg(businesscost) from movies group by 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;
44
Set 5 – Join Queries
Create two tables as follows and write given queries below: Table
- arDst
Table – Song
45
2. Display the records of ar9st and song using equijoin.
3. Display the records of ar9st and song tables using natural join.
mysql > select ar9st_name, label_owner , name from ar9st, song where
ar9st.ar9st_id=song.ar9st_id and label_owner='sony music';
5. Display ar9st name, song name from ar9st and song which song starts with ‘p’.
mysql > select ar9st_name, name from ar9st a, song s where a.ar9st_id =
s.ar9st_id and s.name like ‘p%’;
46
Part C – Python & MySQL Connectivity Programs
Chapter 14 – Interface Python with MySQL
1. Write a program to connect with mysql database and insert a record into
database.
Code: import mysql.connector
as my
cn=my.connect(host='localhost',user='root',passwd='root',database
='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:
2. Write a program to connect with mysql database and update a record into
database.
47
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',database
='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:
3. Write a program to connect with mysql database and delete a record into
database.
48
Code: import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',database
='practical_2025') cur=cn.cursor()
artist_id={}".format(aname,lbl,aid))
cn.close() Output:
Table:
49
4. Write a program to connect with mysql database display record of par9cular
label under the ar9st is working.
Code:
import mysql.connector as my
cn=my.connect(host='localhost',user='root',passwd='root',database
='practical_2025')
cur=cn.cursor()
lbl=input("Enter Label:")
dt=cur.fetchall()
for i in dt:
print(i)
cn.close()
Output:
50