ST MARYS SR.
SECONDARY
CONVENT SCHOOL
Computer science practical file
[Session 2023-24]
SUBMITTED BY : SUBMITTED TO :
NAME – HITESH SHARMA MAM BINDU VASUDEVAN
CLASS – XII B3
ROLL NUMBER –
INDEX:
1
TOPIC PAGE
1. FUNCTIONS 1-6
2. FILE HANDLING 6-12
-TEXT FILES
-BINARY FILES
-CSV FILES
3. DATA STRUCTURE 13
- BSEARCH
- LSEARCH
4. DATABASE 14-16
- INTRODUCTION TO MY SQL
- CREATE TABLES
-QUERIES IN MYSQL
5. INTER FACE PYTHON WITH MY SQL 16-18
-CREATE
-DISPLAY
-DELETE
-MODIFY
Functions:
2
#1. Write a function to accept the length and breadth of the rectangle and
calculate its area.
def arear(l,b):
a=l*b
return(a)
#2. Write a function to accept the side of the square and calculate its area.
def areasq(s):
a=s**2
return(a)
#3. Write a function the radius of the circle and calculate its area.
def areac(r):
a=3.14*r**2
return(a)
#4. Write a function to accept two integers and calculate their sum.
def sumtw(a,b)
s=a+b
return(s)
#5. Write a function to accept a list and a number to be searched in it, search
the number and display how many times the number has occurred in that list.
def count_occurrences(lst, number):
count = lst.count(number)
return(count)
#6. Write a function to accept two integers and return NX.
def m_ply(x, y):
result= x ** y
return (result)
#7. Write a function to accept principal, amount, time and calculate the
simple interest.
3
def calcsi_(principal, rate, time):
interest = (principal * rate * time) / 100
return(interest)
#8. Write a function to accept principal, amount, time and calculate the
compound interest.
def calc_ci(principal, rate, time):
ci = principal * (1 + rate / 100) ** time –
principal
return (ci)
#9. Write a function to accept a list, if the elements are even multiply by 2
otherwise 3.
def modlist(lst):
for i in range(0,len(lst)):
if i%2==0:
lst[i]=i*2
else:
lst[i]=i*3
return(lst)
Y=[2,4,5,6,8,3]
Z=modlist(Y)
print(Z)
#10. Write a function to calculate the factorial of a number.
def calc_fac(number):
if number < 0:
return "Error, no negative numbers..."
elif number == 0 or number == 1:
return 1
else:
factorial = 1
for i in range(2, number + 1):
factorial *= i
return(factorial)
4
#11. Write a function to check whether the string is palindrome or not.
def is_palind(str):
cln_ = str.lower()
cln_= cln_.replace(" ", "")
for i in range(0,len(cln_)):
if cln_[i]==cln_[::-1]:
print("The String is a palindrome")
else:
print("The String is not a palindrome")
#12. Write a function to check whether the number is Armstrong or not.
def is_armstrong(number):
original_number = number
num_digits = len(str(number))
sum_of_cubes = 0
#13. Write a function which gives largest among the three numbers.
def _Lnumber(num1, num2, num3):
x=max(num1, num2, num3)
return(x)
#14. Write a function accepts a list and reverse it.
def reverse_list(input_list):
z=input_list[::-1]
return(z)
#15. Write a function a accept a 2d list and display the sum of even numbers.
def sum_of_even_numbers_2d(_2d_list):
ev_sum = 0
for row in _2d_list:
for num in row:
if num % 2 == 0:
ev_sum += num
5
return(ev_sum)
File Handling
#16. Write a function to read a file comp.txt count the number of words in
the file.
def count_words_in_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
print(f"The file {file_path} was not found.")
return None
#17. Write a function to read the files ,count the number of words starting
with vowel and consonant.
def count_vow_con(file_name):
try:
with open(file_name,'r') as file:
c=0
v=
content=file.read()'
words=content.split()
for i in words:
if i[0] isalpha:
if i[0] in 'AaEeIiOoUu':
v=v+1
else:
c=c+1
print("no. of vowels=" v)
print("no. of consonents=" c)
except FileNotFoundError:
return 0
6
#18. Write a program to create details of a grocery shop with following :
i.)write the data
ii.) Adding records.
iii.) modifying information.
iv.) Search for а particular data.
v.) Removal of unwanted word.
vi.) Displaying report
vii.) Exit
import os
import pickle
def cls():
print("\n"*100)
def mainmenu():
while 1:
print( "welcome to GROCERY STORE".center(45))
print("1. item details")
print("2. exit")
ch= int(input("enter your choice(1-3) : "))
if ch==1:
item_details()
elif ch==2:
print("end of program")
break
else :
print("wrong choice")
def item_details():
while 1:
cls()
print("1. addition")
print("2. modification")
print("3. search")
print("4. deletion")
print("5. display report")
print("6. exit")
7
ck= int(input("enter your choice"))
if ck==1:
add()
elif ck==2:
update()
elif ck==3:
search()
elif ck==4:
remove()
elif ck==5:
report()
elif ck==6:
return
else:
print("wrong choice")
def add():
cls()
xf=open("lakshay.dat","wb")
d={}
ab='y'
while ab=='y':
no= int(input("enter the item no. : "))
desc= input("enter item description : ")
qty=int(input("enter quantity of item :"))
rate=float(input("enter the price of item"))
amt=qty*rate
d['item no']=no
d['description']=desc
d['quantity']=qty
d['rate']=rate
d['amount']=amt
pickle.dump(d,xf)
ab=input("add more records[y/n] : ")
xf.close()
def update():
cls()
xf=open("lakshay.dat","rb+")
d={}
K=True
8
n=int(input("enter the item no. to be updated"))
try:
while K:
k=xf.tell()
d=pickle.load(xf)
if n in d.values():
print(d)
print("1. update quantity of item")
print("2. update rate of item")
ab=int(input("enter your choice(1-2):"))
if ab==1:
q=int(input("enter the new quantity of item"))
d['quantity']=q
elif ab==2:
r=int(input("enter new item rate"))
d['rate']=r
else:
print("wrong choice")
xf.seek(k)
amt=d['quantity']*d['rate']
d['amount']=amt
print(d)
pickle.dump(d,xf)
K=False
except EOFError:
xf.close()
def search():
cls()
xf=open("lakshay.dat","rb")
d={}
n=int(input("enter a number"))
try:
while True:
d=pickle.load(xf)
if n in d.values():
print(d)
except EOFError:
xf.close()
9
def report():
cls()
xf=open("lakshay.dat","rb")
d={}
xf.seek(0)
try:
while True:
d=pickle.load(xf)
print(d)
except EOFError:
xf.close()
def remove():
cls()
xf=open("lakshay.dat","rb")
xy=open("new.dat","wb")
d={}
n=int(input("enter a item no number"))
try:
while True:
d=pickle.load(xf)
if n not in d.values():
pickle.dump(d,xy)
except EOFError:
xf.close()
xy.close()
os.remove("lakshay.dat")
os.rename("new.dat","lakshay.dat")
mainmenu()
#19. csv programs functions
import csv
def create():
xf=open("student.csv","w")
obj= csv.writer(xf,delimiter=':')
obj.writerow(["roll no","Name","marks"])
ab='y'
while ab=='y':
r=int(input("enter roll no."))
n=input("enter name")
10
p=float(input("enter marks"))
obj.writerow([r,n,p])
ab= input("add more records [y/n] :")
xf.close()
create()
import csv
def read_csv(input_file):
with open(input_file, 'r', newline='') as file:
reader = csv.reader(file)
data = [row for row in reader]
return data
def process_data(data):
processed_data = []
for row in data:
row[1] = int(row[1])
processed_data.append(row)
return processed_data
def write_csv(output_file, processed_data):
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(processed_data)
11
Data Structure
#20. Write a function lsearch(l,val) , where l is a list of integers and val is a
integer value passed as argument,Search for the val in the list if found return
1 otherwise 0.
def lsearch(lst, val):
for element in lst:
if element == val:
return 1
else:
return 0
#21. Write a function bsort(l),it consists of list of integers,arrange the data in
the descending order.
def bsort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] < lst[j+1]:
lst[j], lst[j+1] == lst[j+1], lst[j]
#22. Write a function isort(l),l is the list of numbers,arrange the data in
ascending order.
def isort(lst):
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and key < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
database
12
#23. Write a program to create a database “office”, create two tables inside it
and describe them.
CREATE DATABASE IF NOT EXISTS office;
USE office;
CREATE TABLE IF NOT EXISTS employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
CREATE TABLE IF NOT EXISTS departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
#24. Write a program to insert the values in tables created .
INSERT INTO employees (employee_id, first_name, last_name,
department, salary)
VALUES
(1, 'Ayush ', 'Jha', 'HR', 50000.00),
(2, 'Dev', 'Singh', 'IT', 60000.00),
(3, 'Piyush', 'Rajput', 'Finance', 55000.00);
INSERT INTO departments (department_id, department_name)
VALUES
(1, 'HR'),
(2, 'IT'),
(3, 'Finance');
#25. Write a program to retrieve records from tables.
SELECT * FROM employees;
SELECT * FROM departments;
#26. Write a program to retrieve the records from the tables using
conditioning statements.
SELECT employee_id, first_name, last_name FROM employees;
SELECT * FROM employees WHERE department = 'IT';
13
SELECT * FROM employees WHERE salary > 55000;
SELECT * FROM employees WHERE department = 'IT' AND
salary > 55000;
SELECT * FROM employees WHERE department = 'HR' ;
SELECT * FROM employees WHERE department = 'IT' ;
#27. Write a program allowing sorting of query results.
SELECT * FROM employees ORDER BY employee_id;
SELECT * FROM employees ORDER BY salary DESC;
SELECT * FROM employees WHERE salary > 50000 ORDER
BY department, salary DESC;
#28. Write a program to select minimum and maximum value from a give
expression or column.
SELECT MIN(salary) FROM employees;
SELECT MAX(salary) FROM employees;
SELECT MAX(salary) FROM employees WHERE department =
'IT';
#29. Write a program to alter the table structure.
ALTER TABLE employees
ADD COLUMN email VARCHAR(100);
14
#30. Write a program to drop the table from a database.
DROP TABLE IF EXISTS office.employees;
15
Interface with Python
#31. Write a program to connect a sql database to python and displays all the
rows from a table of that database.
import mysql.connector as mc
con=mc.connect(host='localhost',user='root',password='1624',datab
ase='office')
cur=con.cursor()
cur.execute("select * from employees ")
for i in cur:
print(i)
con.commit()
#32. Write a program to insert the values using sql connector in python.
import mysql.connector as mc
con=mc.connect(host='localhost',user='root',password=
‘1624',database='office')
cur=con.cursor()
cur.execute(" insert into employees values(5, 'Ayushi ', 'Singh',
'sales', 55000.00)")
print("RECORDS INSERTED.............")
con.commit()
16
#33. Write a program to update the columns using sql connector in python.
import mysql.connector as mc
con=mc.connect(host='localhost',user='root',password='
1624',database='office')
cur=con.cursor()
name_=input("Enter the name")
new_id=input(" Enter the new id")
cur.execute("update employees set
employee_id='"+new_id+"' where
first_name='"+name_+"'")
print("RECORDS UPDATED.............")
con.commit()
17
CALLING STATEMENTS AND OUTPUTS :
1. length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
area = calculate_rectangle_area(length, breadth)
print("The area of the rectangle is:", area)
2. side = float(input("Enter the side length of the square: "))
area = calculate_square_area(side)
print("The area of the square is:", area)
3. radius = float(input("Enter the radius of the circle: "))
area = calculate_circle_area(radius)
print("The area of the circle is:", area)
4. num_list = [int(x) for x in input("Enter a list of integers separated by
spaces: ").split()]
sum_result = calculate_sum(num_list)
print("The sum of the integers is:", sum_result)
18
5. num_list = [int(x) for x in input("Enter a list of numbers separated by
spaces: ").split()]
target = int(input("Enter the number to search for: "))
occurrences = count_occurrences(num_list, target)
print(f"The number {target} has occurred {occurrences} times in the
list.")
6. N = int(input("Enter the value of N: "))
x = int(input("Enter the value of x: "))
power_result = calculate_power(N, x)
print("{N} raised to the power of {x} is:", power_result)
7. principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the interest rate (%): "))
time = float(input("Enter the time period (years): "))
interest_amount = calculate_simple_interest(principal, rate, time)
print("The simple interest is:", interest_amount”)
19
8. principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the interest rate (%): "))
time = float(input("Enter the time period (years): "))
frequency = int(input("Enter the compounding frequency per year: "))
interest_amount = calculate_compound_interest(principal, rate, time,
frequency)
print("The compound interest is:", interest_amount)
9. num_list = [int(x) for x in input("Enter a list of numbers separated by
spaces: ").split()]
modified_result = modify_list_elements(num_list)
print("Modified list:", modified_result)
10.number = int(input("Enter a number: "))
factorial_result = calculate_factorial(number)
print("The factorial of {number} is:", factorial_result)
11.number = int(input("Enter a number: "))
if is_palindrome(number):
print("{number} is a palindrome.")
else:
print("{number} is not a palindrome.")
20
21
12.number = int(input("Enter a number: "))
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
13.num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
print("Largest:", find_largest(num1, num2, num3))
14.input_string = input("Enter a string: ")
print("Reversed:", reverse_string(input_string))
15.x = int(input("Enter the number of rows: "))
y = int(input("Enter the number of columns: "))
matrix = []
for i in range(x):
row = [int(x) for x in input(f"Enter {y} elements for row {i + 1}
separated by spaces: ").split()]
22
matrix.append(row)
sum_of_even = calculate_sum_of_even_elements(matrix)
print("Sum of even elements in the matrix:", sum_of_even)
16.
17.
18.
23
19.
20. l=eval(input("Enter the list"))
h=int(input("Enter the number to be searched"))
x=lsearch(l,h)
if x == 1:
print(f"{h} is present in the list.")
else:
print(f"{h} is not present in the list.")
24
21. l=eval(input("enter the list"))
bsort(l)
22. l=eval(input("enter a list"))
isort()
23.
24.
25
25.
26.
27.
26
28.
29.
30.
31.
27
32.
33.
28
29