Ram Prakash
Ram Prakash
NO.1 OE TRICHY
PRACTICAL FILE
Page | 1
CERTIFICATE
SIGNATURE OF PRINCIPAL
Page | 2
INDEX
S NO. PRACTICAL PAGE NO. SIGNATURE
1. PRACTICAL 1
2. PRACTICAL 2
3. PRACTICAL 3
4. PRACTICAL 4
5. PRACTICAL 5
6. PRACTICAL 6
7. PRACTICAL 7
8. PRACTICAL 8
9. PRACTICAL 9
10. PRACTICAL 1O
11. PRACTICAL 11
12. PRACTICAL 12
13. PRACTICAL 13
14. PRACTICAL 14
15. PRACTICAL 15
16. PRACTICAL 16
17. PRACTICAL 17
18. PRACTICAL 18
19. PRACTICAL 19
20. PRACTICAL 20
21. PRACTICAL 21
22. PRACTICAL 22
23. PRACTICAL 23
24. PRACTICAL 24
25. PRACTICAL 25
26. PRACTICAL 26
Page | 3
PRACTICAL 1
AIM : To write a menu driven program using functions in python to check a number
- prime or not.
- palindrome or not
- factorial of number
CODE:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
if num % i == 0:
return False
return True
palindrome
def is_palindrome(num):
def factorial(num):
fact = 1
fact *= i
return fact
while True:
print("\nMenu:")
Page | 4
print("2. Check if a number is Palindrome")
print("4. Exit")
if choice == 1:
if is_prime(num):
else:
elif choice == 2:
")) if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
elif choice == 3:
elif choice == 4:
break
else:
OUTPUT:
Page | 5
Page | 6
PRACTICAL 2
AIM : To write a python program using function named largest(a,b,c) which will accept 3 numbers as
parameters and return the largest one. Use the concept of KEYWORD parameters.
CODE :
# Function to find the largest of three
numbers
return max(a, b, c)
OUTPUT :
Page | 7
PRACTICAL 3
AIM : To Write a program to calculate compound interest using function named compint(P,r,n,t) ,where
the default value of rate( r) is 10.
CODE :
# Function to calculate compound interest with default rate
return P * (1 + r / 100) ** (n * t)
#calling function
OUTPUT :
Page | 8
PRACTICAL 4
AIM : To Write a program using function to print Fibonacci series upto n terms. Give default value of n as
15
CODE :
# Function to print Fibonacci series up to n terms
def fibonacci(n=15):
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
a, b = b, a + b
n_terms = input("Enter the number of terms for Fibonacci series (default is 15): ")
fibonacci(n_terms)
OUTPUT :
Page | 9
PROGRAM 5
AIM : To write a program to generate 10 random numbers between 1 to 100
CODE :
import random
def generate_random_numbers():
return random_numbers
print(generate_random_numbers())
OUTPUT :
Page | 10
PRACTICAL 6
AIM : To Write a program to generate the following series
CODE :
# Pattern-1: *
print("Pattern-1:")
print('*' * i)
# Pattern-2: 1 2 3 4
5 print("\nPattern-
2:")
print()
# Pattern-3: A, AB,
ABC
print("\nPattern-3:")
for j in range(i):
Page | 12
OUTPUT :
Page | 13
PRACTICAL 7
AIM : Write a program to enter a list and find the largest and smallest element in the list.
CODE :
# Program to find the largest and smallest element in a list
largest = max(lst)
smallest = min(lst)
OUTPUT :
Page | 14
PRACTICAL 8
AIM : Write a program to enter a list and replace the even elements by their square and odd by their cube
CODE :
# Program to replace even elements by their square and odd elements by their cube
for i in range(len(lst)):
if lst[i] % 2 == 0:
lst[i] = lst[i] ** 2
else:
lst[i] = lst[i] ** 3
OUTPUT :
Page | 15
PRACTICAL 9
AIM : Write a program to enter a tuple and find the sum and average of all the elements
CODE :
# Program to calculate sum and average of elements in a tuple
tup = tuple(map(int, input("Enter numbers for the tuple separated by space: ").split()))
total_sum = sum(tup)
OUTPUT :
Page | 16
PRACTICAL10
AIM : Write a program to create a dictionary having names of your friends as keys and their phone number
as values
CODE :
# Program to create a dictionary with friends' names and their phone
numbers
phonebook = {}
for _ in range(n):
phonebook[name] = phone
print("\nFriends' Phonebook:")
print(f"{name}: {phone}")
OUTPUT :
Page | 17
PRACTICAL 11
AIM : To Write a python program to read and display text file content with each word separated by #.
CODE :
def display_file_content_with_hash():
filename = input("Enter the filename: ")
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
print('#'.join(words))
except FileNotFoundError:
print(f"File '{filename}' not found.")
OUTPUT:
Page | 18
PRACTICAL 12
AIM : To write a python program to copy all the lines that contain the character ‘a’ in a text file “file1.txt”
to another file “file2.txt”.
CODE :
def copy_lines_containing_a():
try:
if 'a' in line:
file2.write(line)
except FileNotFoundError:
copy_lines_containing_a()
OUTPUT :
Page | 19
PRACTICAL 13
AIM : To write a menu driven program using functions to find the following in text file “story.txt”
● Upper case letters
● Lower case letters
● Digits
● Spaces
● vowels
CODE :
def count_uppercase(file):
def count_lowercase(file):
def count_digits(file):
def count_spaces(file):
def count_vowels(file):
vowels = "aeiouAEIOU"
def analyze_text_file():
try:
content = file.read()
print("Select an option:")
Page | 20
print("1. Uppercase letters")
print("3. Digits")
print("4. Spaces")
print("5. Vowels")
if choice == 1:
elif choice == 2:
elif choice == 3:
elif choice == 4:
elif choice == 5:
else:
print("Invalid choice.")
except FileNotFoundError:
analyze_text_file()
OUTPUT :
Page | 21
Page | 22
PRACTICAL 14
AIM : Write a menu driven program using functions to count following in text file “story.txt”
● Total words
● Words having length 5
● “hello”
CODE :
def count_total_words(file):
return len(file.split())
def count_words_of_length_5(file):
def count_hello(file):
return file.split().count('hello')
def analyze_word_counts():
try:
content = file.read()
print("Select an option:")
if choice == 1:
elif choice == 2:
Page | 23
print(f"Words of length 5: {count_words_of_length_5(content)}")
elif choice == 3:
else:
print("Invalid choice.")
except FileNotFoundError:
analyze_word_counts()
OUTPUT :
Page | 24
PRACTICAL 15
AIM :To write a menu driven program to find the following in text file “story.txt”
● To count lines starting with ‘P’ or ‘T’
● To count lines starting with vowels
CODE :
def count_lines_starting_with_pt(file):
def count_lines_starting_with_vowel(file):
vowels = ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u')
def analyze_lines():
try:
lines = file.readlines()
print("Select an option:")
if choice == 1:
elif choice == 2:
else:
print("Invalid choice.")
except FileNotFoundError:
Page | 25
print(f"File '{filename}' not found.")
analyze_lines()
OUTPUT :
Page | 26
PRACTICAL 16
AIM : To Write a python program to create a binary file with roll number, name and address. Search for a
given roll number and display name and address , if not found display appropriate message.
CODE :
import pickle
def create_binary_file():
for _ in range(n):
pickle.dump(student, file)
def search_roll_number():
found = False
try:
while True:
student = pickle.load(file)
if student[0] == roll_no_to_search:
found = True
break
except EOFError:
if not found:
create_binary_file()
search_roll_number()
OUTPUT :
Page | 28
PRACTICAL 17
AIM : To write a python program to create a binary file with roll number, name and marks, input a roll
number and update the marks
CODE :
import pickle
def create_binary_file():
for _ in range(n):
pickle.dump(student, file)
def update_marks():
found = False
students = []
try:
while True:
student = pickle.load(file)
if student[0] == roll_no_to_update:
Page | 29
found = True
students.append(student)
except EOFError:
pass
if found:
pickle.dump(student, file)
else:
create_binary_file()
update_marks()
OUTPUT :
Page | 30
PRACTICAL 18
AIM : A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and
return number of books by the given Author are stored in the binary file “Book.dat”
CODE :
import pickle
def create_file():
while True:
pickle.dump(book, file)
if more.lower() != 'y':
break
def count_rec(author_name):
count = 0
try:
while True:
book = pickle.load(file)
if book[2].lower() == author_name.lower():
count += 1
except EOFError:
pass
Page | 31
return count
create_file()
count = count_rec(author_name)
OUTPUT :
Page | 32
PRACTICAL 19
AIM : . A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those students
whose percentage is above 75. Also display number of students scoring above 75%
CODE :
import pickle
def count_rec():
count = 0
try:
while True:
student = pickle.load(file)
count += 1
except EOFError:
pass
# Call function
count_rec()
OUTPUT :
Page | 33
PRACTICAL 20
AIM : To write a python program to create a CSV file with empid, name and mobile no. and search empid,
update the record and display the records.
CODE :
import csv
def create_csv_file():
writer = csv.writer(file)
for _ in range(n):
def search_and_update_record():
found = False
rows = []
reader = csv.reader(file)
if row[0] == emp_id_to_search:
print(f"Found: {row}")
Page | 34
new_mobile = input("Enter new mobile number: ")
row[1] = new_name
row[2] = new_mobile
found = True
rows.append(row)
if found:
writer.writerows(rows)
else:
create_csv_file()
search_and_update_record()
OUTPUT :
Page | 35
PRACTICAL 21
AIM : To write a Program in Python to create a stack named ‘book’ which contains these book details :
(bookno, book name). That is, now each item node ofthe stack containstwo types of information – a
bookno and its name. Implement Push, Pop, and Traversal operations on the stack.
CODE :
class Stack:
self.stack = []
self.stack.append((bookno, bookname))
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty.")
def is_empty(self):
return len(self.stack) == 0
def traverse(self):
if not self.is_empty():
print(book)
else:
print("Stack is empty.")
# Create stack
Page | 36
book_stack = Stack()
# Push books
# Traverse stack
book_stack.traverse()
# Pop book
book_stack.pop()
book_stack.traverse()
OUTPUT :
Page | 37
PRACTICAL 22
AIM : To find each node of a STACK contains the following information: (i) Pin code of a city, (ii) Name of
city. Write a program to implement following operations on above stack.
CODE :
class CityStack:
self.stack = []
self.stack.append((pin_code, city_name))
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty.")
def is_empty(self):
return len(self.stack) == 0
def traverse(self):
if not self.is_empty():
print(city)
else:
print("Stack is empty.")
Page | 38
# Create stack
city_stack = CityStack()
# Push city
city_stack.push(110001, "Delhi")
city_stack.push(500001, "Hyderabad")
# Traverse stack
city_stack.traverse()
# Pop city
city_stack.pop()
city_stack.traverse()
OUTPUT :
Page | 39
PRACTICAL 23
AIM : To Write a python program to create stack Sport_Stack to store age of sportsman using
stack implementation as list. Write Operation for Push, Pop and Traversal operation using menu.
CODE :
class SportStack:
def init (self):
self.stack = []
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty.")
def is_empty(self):
return len(self.stack) == 0
def traverse(self):
if not self.is_empty():
for age in self.stack:
print(age)
else:
print("Stack is empty.")
# Create stack
sport_stack = SportStack()
# Traverse stack
sport_stack.traverse()
OUTPUT :
Page | 40
Page | 41
PRACTICAL 24
AIM:Create a CLUB table as mentioned with given data type and constraints. Table - CLUB
and insert data as given below in this using suitable SQL statements.
COACH_ COACHNAM AGE SPORTS DATOFAP PAY SEX
ID E P
1 KUKREJA 35 KARATE 27/03/1996 1000 M
2 RAVINA 34 KARATE 20/01/1998 1200 F
3 KARAN 34 SQUASH 19/02/1998 2000 M
4 TARUN 33 BASKETBALL 01/01/1998 1500 M
5 ZUBIN 36 SWIMMING 12/01/1998 750 M
6 KETAKI 36 SWIMMING 24/02/1998 800 F
7 ANKITA 39 SQUASH 20/02/1998 2200 F
8 ZAREEN 37 KARATE 22/02/1998 1100 F
9 KUSH 41 SWIMMING 13/01/1998 NULL M
10 SHAILYA 37 BASKETBALL 19/02/1998 1700 M
INSERT INTO CLUB (coach_id, coachname, age, sports, datofapp, pay, sex) VALUES
(1, 'KUKREJA', 35, 'KARATE', '1996-03-27', 1000, 'M'),
(2, 'RAVINA', 34, 'KARATE', '1998-01-20', 1200, 'F'),
(3, 'KARAN', 34, 'SQUASH', '1998-02-19', 2000, 'M'),
(4, 'TARUN', 33, 'BASKETBALL', '1998-01-01', 1500, 'M'),
(5, 'ZUBIN', 36, 'SWIMMING', '1998-01-12', 750, 'M'),
(6, 'KETAKI', 36, 'SWIMMING', '1998-02-24', 800, 'F'),
(7, 'ANKITA', 39, 'SQUASH', '1998-02-20', 2200, 'F'),
(8, 'ZAREEN', 37, 'KARATE', '1998-02-22', 1100, 'F'),
(9, 'KUSH', 41, 'SWIMMING', '1998-01-13', NULL, 'M'),
(10, 'SHAILYA', 37, 'BASKETBALL', '1998-02-19', 1700, 'M');
OUTPUT:
Page | 42
Page | 43
Page | 44
Page | 45
PRACTICAL 25
AIM:In a database there are two tables “Product” and “Client” as shown below
:Table – Product
P_ID Product_Name Manufacture Price
P004
P005
Table – Client
C_ID ClientName City P_ID
01 Dreamz Disney New Delhi P002
05 Life Line Inc Mumbai P005
12 98.4 New Delhi P001
15 Appolo Banglore P003
Write the commands in SQL queries for the following:
1.) To display the details of product whose price is in range of 40 and 120 ( both
values included).
2.) To display the client name , city from table client and product name and price from
table product , with their corresponding matching P_ID.
3.) To increase the price of all the products by 20.
4.) To display product details where client belongs to ‘New Delhi’.
5.) To list all the products who do not have any client in ‘New Delhi’ and ‘Mumbai’
.
6.) To display number of clients in each city.
7.) To list all the clients having product price maximum rs. 50.
8.) To display product name and its price with decreasing order of price.
9.) To display total no. of products.
10.) Show the average price for all products.
CODE:
1. SELECT * FROM Product WHERE Price BETWEEN 40 AND 120;
2. SELECT Client.ClientName, Client.City, Product.Product_Name, Product.Price FROM Client
INNER JOIN Product ON Client.P_ID = Product.P_ID;
3. UPDATE Product SET Price = Price + 20;
4. SELECT Product.* FROM Product INNER JOIN Client ON Product.P_ID = Client.P_ID
WHERE Client.City = 'New Delhi';
5. SELECT * FROM Product WHERE P_ID NOT IN (SELECT P_ID FROM Client WHERE City
IN ('New Delhi', 'Mumbai'));
6. SELECT City, COUNT(*) AS ClientCount FROM Client GROUP BY City;
Page | 46
7. SELECT Client.ClientName FROM Client INNER JOIN Product ON Client.P_ID =
Product.P_ID WHERE Product.Price<= 50;
8. SELECT Product_Name, Price FROM Product ORDER BY Price DESC;
9. SELECT COUNT(*) AS TotalProducts FROM Product;
10. SELECT AVG(Price) AS AveragePrice FROM Product;
OUTPUT:
Page | 47
Page | 48
PRACTICAL 26
AIM:Write a menu-driven program which integrates MySQL and Python connectivity with
the table BOOKS whose content is given below. Create the database named LIBRARY.
Database Name- LIBRARY
Table Name- BOOKS
Make Book_id as the primary key.
Write the following functions for the same
a) Adding record
b) Deleting record
c) Updating record
d) Searching record
e) Showing all data
CODE:import mysql.connector
def connect_to_database():
return mysql.connector.connect(
host="host",
user="root",
password="1234",
database= "library"
)
def create_table():
db = connect_to_database()
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS BOOKS
( Book_id INT PRIMARY KEY,
Book_nameVARCHAR(255),
Author VARCHAR(255),
Price DECIMAL(10, 2)
)
""")
db.commit()
cursor.close()
db.close()
print("Table created successfully.")
def insert_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID: "))
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Book Price: "))
cursor.execute("""
INSERT INTO BOOKS (Book_id, Book_name, Author, Price)
VALUES (%s, %s, %s, %s)
Page | 49
""", (book_id, book_name, author, price))
db.commit()
cursor.close()
db.close()
print("Book inserted successfully.")
def display_books():
db = connect_to_database()
cursor = db.cursor()
cursor.execute("SELECT * FROM BOOKS")
books = cursor.fetchall()
if books:
for book in books:
print(f"Book ID: {book[0]}, Book Name: {book[1]}, Author: {book[2]}, Price: {book[3]}")
else:
print("No books found.")
cursor.close()
db.close()
def update_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID to update: "))
new_price = float(input("Enter new price for the book: "))
cursor.execute("""
UPDATE BOOKS
SET Price = %s
WHERE Book_id = %s
""", (new_price, book_id))
db.commit()
cursor.close()
db.close()
print("Book price updated successfully.")
def delete_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID to delete: "))
cursor.execute("""
DELETE FROM BOOKS
WHERE Book_id = %s
""", (book_id,))
db.commit()
cursor.close()
db.close()
print("Book deleted successfully.")
Page | 50
def main():
while True:
print("\nLIBRARY MENU")
print("1. Create Table")
print("2. Insert Book")
print("3. Display All Books")
print("4. Update Book Price")
print("5. Delete Book")
print("6. Exit")
if choice == 1:
create_table()
elif choice == 2:
insert_book()
elif choice == 3:
display_books()
elif choice == 4:
update_book()
elif choice == 5:
delete_book()
elif choice == 6:
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
if _name_ == "_main_":
main()
OUTPUT:
Page | 51
Page | 52