Computer Science Practical file
Computer Science Practical file
PRACTICAL FILE
Submitted by: Sumit Bhatt (XII- A)
INDEX
DATE AIM REMARKS
Python Functions-
24 April 2024 1. Write a function to check if a given number is prime
14 August 2024 6.Write a program to read employee data from a text file
and print employees with salary > 5000.
21 August 2024 7. Write a program to read words from a text file and
create two separate files - one with words starting with 'a' and another
25 September 12. Write a program to read all content of "student.csv" and display
2024 records of only those students who scored more than 80 marks.
Records stored in students is in
format: Roll no., Name
Disease, AdmitDate)
13 November
1. Write SQL queries to:
2024
Quantity, Date)
20 November
2. Write SQL queries to:
2024
Sport, Hours)
27 November
3. Write SQL queries to:
2024
04 December
4. Write SQL queries to:
2024
04 December
5. Write SQL queries to:
2024
PYTHON-SQL CONNECTIVITY
11 December 1. Write a program to create a hospital management
2024 System
OUTPUT:
PRACTICAL-2
OUTPUT:
PRACTICAL-3
AIM: Write a program to find the greatest number in each list of numbers
using a function.
INPUT:
def find_greatest(numbers):
greatest = numbers[0]
for num in numbers:
if num > greatest:
greatest = num
return greatest
list = eval(input("Enter the list: "))
print(f"Greatest in {list} is:", find_greatest(list))
OUTPUT:
PRACTICAL-4
# Test
if name == " main ":
test_string = "The quick brown fox jumps over the lazy
dog"
print(f"Is pangram? {is_pangram(test_string)}")
OUTPUT
PRACTICAL-5
OUTPUT:
PRACTICAL-6
AIM: Write a program to read employee data from a text file and print
employees with salary > 5000.
INPUT:
print("Filtered Employe Records (Salary > 5000):")
f = open("employees.txt", 'r')
for line in f:
name, position, salary = line.strip().split(", ")
if int(salary) > 5000:
print(f"Name: {name}, Position: {position}, Salary:
{salary}")
f.close()
OUTPUT:
PRACTICAL-7
AIM: Write a program to read words from a text file and create two separate
files - one with words starting with 'a' and another with remaining words.
INPUT:
OUTPUT
PRACTICAL-8
AIM: Write a program to find and replace specific words in a text file
INPUT:
filename="text_handling/story.txt"
old_word=input("Word to replace: ")
new_word=input("Replace with: ")
file=open(filename,'r')
content=file.read()
file.close()
print("\nOriginal content:")
print(content)
new_content=""
i=0
while i<len(content):
if content[i:i+len(old_word)]==old_word:
new_content+=new_word
i+=len(old_word)
else:
new_content+=content[i]
i+=1
file=open(filename,'w')
file.write(new_content)
file.close()
print(f"\nReplaced all occurrences of '{old_word}' with
'{new_word}'")
print("\nNew content:")
print(new_content)
OUTPUT:
PRACTICAL-9
AIM: Write a program to store names and surnames in a binary file and display
records where name/surname starts with 'a.’
INPUT:
import pickle
file = open('usernames.dat', 'rb')
loaded_usernames = pickle.load(file)
filtered_usernames = []
for username in loaded_usernames:
if username.startswith('a'):
filtered_usernames.append(username)
if filtered_usernames:
print("All usernames:", loaded_usernames)
print("\nUsernames starting with 'a':", filtered_usernames)
else:
print("No usernames start with 'a'.")
file.close()
OUTPUT:
PRACTICAL-10
AIM: Write a program to store movie details and display movies by genre/year
INPUT:
import pickle
from typing import Dict, List, Optional
from datetime import datetime
class Movie:
def init (self, title: str, year: int, genre: str, director: str, rating:
float):
self.title = title
self.year = year
self.genre = genre
self.director = director
self.rating = rating
class MovieDatabase:
def init (self, filename: str):
self.filename = filename
self.movies: List[Movie] = []
self.load_database()
def load_database(self):
try:
with open(self.filename, 'rb') as f:
self.movies = pickle.load(f)
except (FileNotFoundError, EOFError):
self.movies = []
def save_database(self):
with open(self.filename, 'wb') as f:
pickle.dump(self.movies, f)
def add_movie(self, title: str, year: int, genre: str, director: str,
rating: float) -> bool:
movie = Movie(title, year, genre, director, rating)
self.movies.append(movie)
self.save_database()
return True
def get_movies_by_genre(self, genre: str) -> List[Movie]:
return [movie for movie in self.movies if movie.genre.lower()
== genre.lower()]
def get_movies_by_year(self, year: int) -> List[Movie]:
return [movie for movie in self.movies if movie.year == year] def
display_movies(self, movies: List[Movie]):
if not movies:
print("No movies found!")
return
print("\n" + "="*50)
for movie in movies:
print(f"Title: {movie.title}") print(f"Year:
{movie.year}")
print(f"Genre: {movie.genre}")
print(f"Director: {movie.director}")
print(f"Rating: {movie.rating}/10") print("-
"*50)
OUTPUT:
PRACTICAL-11
AIM: Write a program to modify marks of a specific student in a binary file
containing student records.
INPUT:
import pickle
with open("binary_handling/student.dat","ab") as f:
rollno=int(input("Enter Roll Number: "))
name=input("Enter Name: ")
marks=int(input("Enter Marks: "))
rec=[rollno,name,marks]
pickle.dump(rec,f)
OUTPUT
PRACTICAL-12
import csv
f = open("student.csv", "r")
d = csv.reader(f)
next(f)
print("Students Scored More than 80")
print()
for i in d:
if int(i[2]) > 80:
print("Roll Number =", i[0])
print("Name =", i[1])
print("Marks =", i[2])
print("-")
f.close()
OUTPUT:
PRACTICAL-13
AIM: Write a program to store student records in a CSV file and display students
having marks above a given threshold
import csv
def create_student_records():
with open('students.csv', 'w', newline='') as file: writer =
csv.writer(file)
writer.writerow(['Roll', 'Name', 'Marks'])
def find_students_above_threshold():
threshold = float(input("\nEnter marks threshold: ")) print(f"\nStudents with marks above
{threshold}:")
create_student_records()
find_students_above_threshold()
OUTPUT:
PRACTICAL-14
AIM: Create a password generator with options for length and character
types (numbers)
import random
def create_password(length):
numbers='0123456789'
password=''
for i in range(length): password+=random.choice(numbers)
return password
print("Simple Password Generator") print("-
"*25)
length=int(input("Password length: "))
print("\nHere are 5 password options:") print("-
"*25)
for i in range(5):
password=create_password(length) print(f"Option
{i+1}: {password}")
OUTPUT
PRACTICAL-15
AIM: Write a program to implement multiple stacks in a single array
def stack_operations():
stack = []
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("Enter item to push: ")
stack.append(item)
print(f"{item} pushed to stack")
elif choice == '2':
if stack:
print(f"{stack.pop()} popped from stack")
else:
print("Stack is empty")
elif choice == '3':
if stack:
print(f"Top element is: {stack[-1]}")
else:
print("Stack is empty")
elif choice == '4':
if stack:
print("\nStack elements from top:")
for item in reversed(stack):
print(f"| {item} |")
print("-" * 20)
else:
print("Stack is empty")
elif choice == '5':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again")
if name == " main ":
stack_operations()
OUTPUT:
PRACTICAL-16
AIM: Write a program to sort a stack using only push and pop operations
def sort_stack(stack):
temp_stack = []
while stack:
temp = stack.pop()
while temp_stack and temp_stack[-1] > temp:
stack.append(temp_stack.pop())
temp_stack.append(temp)
while temp_stack:
stack.append(temp_stack.pop())
return stack
if name == " main ":
test_stack = []
test_data = [5, 2, 9, 1, 7, 6, 3]
print("Original stack:")
for item in test_data:
test_stack.append(item)
print(item, end=" ")
print()
sorted_stack = sort_stack(test_stack)
print("\nSorted stack:")
for item in sorted_stack:
print(item, end=" ")
print()
OUTPUT:
PRACTICAL-17
AIM: Write SQL queries : HOSPITAL
Table
PATIENT Table
CREATE TABLE PATIENTS (PatientID INT PRIMARY KEY, Name VARCHAR(100),
DoctorID INT, Disease VARCHAR(100), AdmitDate DATE, FOREIGN KEY
(DoctorID) REFERENCES HOSPITAL(DoctorID));
INSERT INTO PATIENTS VALUES(PatientID,Name,DoctorID,Disease,AdmitDate)
(1, 'John Doe', 1, 'Heart Disease', '2024-01-15'),
(2, 'Jane Smith', 2, 'Flu', '2024-02-01'),
(3, 'Bob Wilson', 1, 'Hypertension', '2024-01-20'),
(4, 'Alice Brown', 3, 'Migraine', '2024-02-10'),
(5, 'Charlie Davis', 4, 'Fracture', '2024-02-15');
1. Find doctors with more than 10 patients
SELECT h.Name, COUNT(p.PatientID) as PatientCount FROM HOSPITAL h LEFT JOIN
PATIENTS p ON h.DoctorID = p.DoctorID GROUP BY h.DoctorID, h.Name HAVING
COUNT(p.PatientID) > 10;
RESTURANT Table
CREATE TABLE RESTAURANT (ItemID INT PRIMARY KEY, Name VARCHAR(100) NOT
NULL, Category VARCHAR(50) NOT NULL, Price DECIMAL(10,2) NOT NULL);
INSERT INTO RESTAURANT VALUES
(1, 'Margherita Pizza', 'Pizza', 12.99),
(2, 'Chicken Alfredo', 'Pasta', 15.99),
(3, 'Caesar Salad', 'Salad', 8.99),
(4, 'Chocolate Cake', 'Dessert', 6.99),
(5, 'Espresso', 'Beverages', 3.99),
(6, 'Garlic Bread', 'Appetizer', 4.99);
ORDER Table
CREATE TABLE ORDERS (OrderID INT PRIMARY KEY, TableNo INT NOT NULL, ItemID
INT, Quantity INT NOT NULL, Date DATETIME NOT NULL, FOREIGN KEY (ItemID)
REFERENCES RESTAURANT(ItemID));
INSERT INTO ORDERS VALUES
(1, 1, 1, 2, '2024-03-15 18:30:00'),
(2, 2, 2, 1, '2024-03-15 19:00:00'),
(3, 1, 3, 1, '2024-03-15 18:35:00'),
(4, 3, 1, 1, '2024-03-15 20:00:00'),
(5, 2, 4, 2, '2024-03-15 19:30:00'),
(6, 4, 2, 2, '2024-03-15 20:30:00');
1. Find most ordered items
SELECT
r.Name,
COUNT(*) as OrderCount,
SUM(o.Quantity) as TotalQuantity
FROM RESTAURANT r
JOIN ORDERS o ON r.ItemID = o.ItemID
GROUP BY r.ItemID, r.Name
ORDER BY TotalQuantity DESC;
OUTPUT:
PRACTICAL-19
SPORTS_CLUB Table
CREATE TABLE SPORTS_CLUB (MemberID INT PRIMARY KEY, Name
VARCHAR(100) NOT NULL, JoinDate DATE NOT NULL, Plan
VARCHAR(50) NOT NULL);
INSERT INTO SPORTS_CLUB VALUES(MemberID, Name, JoinDate, Plan)
(1, 'John Smith', '2023-01-15', 'Premium'),
(2, 'Sarah Johnson', '2023-03-20', 'Basic'),
(3, 'Mike Wilson', '2023-02-10', 'Premium'),
(4, 'Emma Davis', '2023-04-05', 'Basic'),
(5, 'Tom Brown', '2023-01-01', 'Premium'),
(6, 'Lisa Anderson', '2023-05-15', 'Basic');
ACTIVITIES Table
CREATE TABLE ACTIVITIES (ActivityID INT PRIMARY KEY, MemberID INT,
Sport VARCHAR(50) NOT NULL, Hours DECIMAL(5,2) NOT NULL,
ActivityDate DATE NOT NULL, FOREIGN KEY (MemberID) REFERENCES
SPORTS_CLUB(MemberID));
INSERT INTO ACTIVITIES VALUES(ActivityID, MemberID, Sport,
Hours,ActivityDate)
(1, 1, 'Tennis', 2.0, '2024-03-15'),
(2, 1, 'Swimming', 1.5, '2024-03-16'),
(3, 2, 'Yoga', 1.0, '2024-03-15'),
(4, 3, 'Tennis', 1.5, '2024-03-15'),
(5, 4, 'Swimming', 1.0, '2024-03-16'),
(6, 5, 'Tennis', 2.0, '2024-03-16');
1. List members by activity hours
SELECT sc.Name, SUM(a.Hours) as TotalHours, COUNT(DISTINCT a.Sport) as
DifferentSports FROM SPORTS_CLUB sc LEFT JOIN ACTIVITIES a ON
sc.MemberID = a.MemberID GROUP BY sc.MemberID, sc.Name ORDER BY
TotalHours DESC;
REVIEWS Table
CREATE TABLE REVIEWS (ReviewID INT PRIMARY KEY, ProductID INT, Rating INT CHECK
(Rating BETWEEN 1 AND 5), Comment TEXT, ReviewDate DATE NOT NULL, FOREIGN KEY
(ProductID) REFERENCES E_COMMERCE(ProductID));
INSERT INTO REVIEWS VALUES
(1, 1, 5, 'Great phone!', '2024-03-01'),
(2, 1, 4, 'Good but expensive', '2024-03-02'),
(3, 2, 5, 'Very comfortable', '2024-03-03'),
(4, 3, 3, 'Average product', '2024-03-04'),
(5, 4, 5, 'Excellent laptop', '2024-03-05'),
(6, 1, 4, 'Nice features', '2024-03-06');
1. Find products with best reviews
SELECT e.Name, COUNT(r.ReviewID) as ReviewCount, AVG(r.Rating) as AvgRating,
MIN(r.Rating) as MinRating, MAX(r.Rating) as MaxRating FROM E_COMMERCE e LEFT
JOIN REVIEWS r ON e.ProductID = r.ProductID GROUP BY e.ProductID, e.Name HAVING
ReviewCount > 0 ORDER BY AvgRating DESC, ReviewCount DESC;
BOOKS Table
CREATE TABLE BOOKS (BookID INT PRIMARY KEY, Title VARCHAR(200) NOT NULL,
Author VARCHAR(100) NOT NULL, Category VARCHAR(50) NOT NULL, Available
BOOLEAN DEFAULT TRUE);
INSERT INTO BOOKS VALUES
(1, 'Database Systems', 'Thomas Anderson', 'Technical', TRUE),
(2, 'Modern Physics', 'Robert Smith', 'Science', TRUE),
(3, 'World History', 'Emma Thompson', 'History', TRUE),
(4, 'Programming in Python', 'John Davis', 'Technical', TRUE),
(5, 'Organic Chemistry', 'Lisa Wilson', 'Science', TRUE)
TRANSACTIONS Table
CREATE TABLE TRANSACTIONS (TransID INT PRIMARY KEY, BookID INT, MemberID INT,
IssueDate DATE NOT NULL, ReturnDate DATE, DueDate DATE NOT NULL, FOREIGN KEY
(BookID) REFERENCES BOOKS(BookID), FOREIGN KEY (MemberID) REFERENCES
LIBRARY_MEMBERS(MemberID));
INSERT INTO TRANSACTIONS VALUES
(1, 1, 1, '2024-03-01', '2024-03-15', '2024-03-15'),
(2, 2, 2, '2024-03-05', NULL, '2024-03-19'),
(3, 3, 3, '2024-03-10', '2024-03-17', '2024-03-24'),
(4, 4, 1, '2024-03-15', NULL, '2024-03-29'),
(5, 5, 4, '2024-03-12', NULL, '2024-03-26');
1. Find members with overdue books
SELECT m.MemberID, m.Name, m.Type, b.Title, t.IssueDate, t.DueDate,
DATEDIFF(CURRENT_DATE, t.DueDate) as DaysOverdue FROM LIBRARY_MEMBERS m
JOIN TRANSACTIONS t ON m.MemberID = t.MemberID JOIN BOOKS b ON t.BookID =
b.BookID WHERE t.ReturnDate IS NULL AND t.DueDate < CURRENT_DATE ORDER BY
DaysOverdue DESC;
def create_student_table():
conn = None
cursor = None
try:
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root",password="@goth",
database="school")
cursor = conn.cursor()
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if cursor:
cursor.close()
if conn and conn.is_connected():
conn.close()
print("MySQL connection closed")
def insert_student_records():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()
conn.commit()
print("\nRecords inserted successfully")
except mysql.connector.Error as e:
print(f"Database Error: {e}")
except ValueError as e:
print(f"Input Error: Please enter valid data")
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection closed")
def display_and_search():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()
while True:
print("\n=== Student Record System ===")
print("1. Display all records")
print("2. Search by name")
print("3. Exit")
print("=" * 26)
if choice == '1':
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
print("\nStudent Records:")
print("-" * 60)
print("Roll No | Name | Class | Marks")
print("-" * 60)
for record in records:
print(f"{record[0]:^8} | {record[1]:<12} | {record[2]:^7} | {record[3]:>6.2f}")
print("-" * 60)
else:
print("\nInvalid choice! Please enter 1, 2, or 3")
except mysql.connector.Error as e:
print(f"\nDatabase Error: {e}")
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("\nDatabase connection closed")
OUTPUT:
PRACTICAL-25
Write a program to update and delete student records based on roll number
import mysql.connector
2|
def update_delete_records():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()
while True:
print("\n=== Student Record Management ===\n1. Update student marks\n2. Delete
student record\n3. Exit\n" + "=" * 30)
choice = input("Enter your choice (1-3): ")
if choice == '1':
try:
roll_no, new_marks = int(input("Enter roll number to update: ")), float(input("Enter
new marks (0-100): "))
if 0 <= new_marks <= 100:
cursor.execute("UPDATE students SET marks = %s WHERE roll_no = %s",
(new_marks, roll_no))
conn.commit()
print("\nMarks updated successfully" if cursor.rowcount > 0 else "\nStudent not
found")
else: print("\nMarks must be between 0 and 100")
except ValueError: print("\nPlease enter valid numbers")
OUTPUT: