PracticalFile HITESH
PracticalFile HITESH
SECONDARY
CONVENT SCHOOL
SUBMITTED BY : SUBMITTED TO :
INDEX:
1
TOPIC PAGE
1. FUNCTIONS 1-6
3. DATA STRUCTURE 13
- BSEARCH
- LSEARCH
4. DATABASE 14-16
- INTRODUCTION TO MY SQL
- CREATE TABLES
-QUERIES IN MYSQL
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.
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.
#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 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()
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
11
Data Structure
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)
);
13
SELECT * FROM employees WHERE salary > 55000;
#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;
14
#30. Write a program to drop the table from a database.
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)
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.")
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)
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.")
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.
24
21. l=eval(input("enter the list"))
bsort(l)
23.
24.
25
25.
26.
27.
26
28.
29.
30.
31.
27
32.
33.
28
29