COMPUTER
SCIENCE
PRACTICAL FILE
Submitted by: Pranjal Aggarwal
Class: XII-A
Roll No : 12114
INDEX
S.No Programs
1 Program to Find the Fibonacci Sequence Up to
n Terms
2 Program to Check if a Number is Prime
3 Program to Check if a String is a Palindrome
4 Program to Count the Number of Vowels in a
String
5 Program to Calculate Simple Interest
6 Program to Write to a Text File
7 Read from a Text File
8 Count Words in a Text File
9 Random Number Game
10 SQL queries using one table
Creating a table
Insert 5 entries
Display employees in “HR” department
To find highest salary in the company
Count the number of employees in each
department
11 SQL queries using two tables
Creating a table”employees” and
table”department”
Insert 5 entries
Join both tables
List departments with an average salary
greater than $60000
Find employees working in “IT”
department
12 SQL queries using one table
Retrieve all employees in the IT
department
Find the average salary of all employees
List employees hired after January 1 ,
2020
Count the number of employees in each
department
Get the employee with the highest salary
13 SQL queries using two tables
List all books available in a specific
library
Find the total number of available copies
for all books in each library
Retrieve books with no available copies
Count the number of books in each
library
Find the libraries that have books by a
specific author
14 SQL queries using one table
Retrieve all hotels with a rating above 4.0
Find the total number of available rooms
across all hotels
List hotels located in New York or miami
Calculate the average price per night of
all hotels
Get the hotel with the highest rating
15 Program to input name of a student and
marks for 5 students and write it in a file
stud.csv
16 Program to input roll number , name and
marks for 5 students and write to the file
mark.csv
17 program to input roll number and name from
the users for 5 students and then write onto a
binary file S1.dat
18 program to input a dictionary name e1 with
employee number and name to a file emp.dat
19 program to write a dictionary named s1 with
employee name and salary to a file sal.dat
20 Write a program to connect to MYSQL
database and create a table
21 Write a program to insert multiple student
records with user input
22 Write a program to display all records and
implement name base search
23 Write a program to update hostel rating to 5.0
24 Write a program to check paranthesis in an
expression are balanced using stack
Program to Find the Fibonacci Sequence
Up to n Terms
Input:
Output:
Program to Check if a Number is Prime
Input:
Output:
Program to Check if a String is a
Palindrome
Input:
Output:
Program to Count the Number of
Vowels in a String
Input:
Output:
Program to Calculate Simple
Interest
Input:
Output:
Program to Write to a Text File
Input:
Output:
Read from a Text File
Input:
Example.txt:
Output:
Count Words in a Text File
Input:
Example.txt:
Output:
Random Number Game
Input:
Output:
SQL QUERIES USING ONE
TABLE
Creating a table:
Insert 5 entries:
1. Select all employees in the 'HR'
department:
2. Find the highest salary in the
company:
3. Count the number of employees
in each department:
SQL QUERIES USING TWO
TABLES
Creating tables:
Table 1 Employees:
Insert 5 entries:
Table 2 Department:
Insert 5 entries:
1. Join both tables to get
employee names and their
department names:
2. List departments with an
average salary greater than
$60,000:
3. Find employees working in
the 'IT' department:
SQL QUERIES USING ONE TABLE
Creating tables:
Insert 5 entries:
1.Retrieve all employees in the IT
department:
2. Find the average salary of all
employees:
3.List employees hired after
January 1, 2020:
4.Count the number of employees
in each department:
5.Get the employee with the
highest salary:
SQL QUERIES USING TWO TABLES
Creating tables “Book” and
“Library”:
Inserting Data:
1.List all books available in a
specific library:
2. Find the total number of available
copies for all books in each library:
3.Retrieve books with no available
copies:
4.Count the number of books in
each library:
5.Find the libraries that have books
by a specific author:
SQL QUERIES USING ONE TABLE
Creating table:
Insert 5 entries:
1. Retrieve all hotels with a rating
above 4.0:
2.Find the total number of available
rooms across all hotels:
3.List hotels located in New York or
Miami:
4.Calculate the average price per
night of all hotels:
5.Get the hotel with the highest
rating:
Program to input name of a student
and marks for 5 students and write
it in a file stud.csv
Input:
Output:
Program to input roll number , name and
marks for 5 students and write to the
file mark.csv
Input:
Output:
Program to input roll number and
name from the users for 5 students
and then write onto a binary file
S1.dat
Input:
Output:
Program to input a dictionary name
e1 with employee number and
name
to a file emp.dat
Input:
Output:
Program to write a dictionary
named s1 with employee name and
salary to a file sal.dat
Input:
Output:
Write a Program to connect to
MYSQL database and create a
table:
Input:
import mysql.connector
# Connect to MySQL
connection = mysql.connector.connect(
host='localhost',
user='root',
password='1909',
database='testdb'
)
# Create a table
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE Hostel(
HostelID INT PRIMARY KEY AUTO_INCREMENT,
HostelName VARCHAR(100),
Location VARCHAR(100),
Rating DECIMAL(2, 1),
RoomsAvailable INT,
PricePerNight DECIMAL(10, 2)
)
""")
print("Table 'Hostel' created successfully.")
# Close the connection
cursor.close()
connection.close()
Output:
Write a Program to insert multiple
student records with user input:
Input:
import mysql.connector
def insert_hostel_records():
"""Insert multiple records into the Hostel table with the specified columns,
including HostelID."""
try:
# Connect to MySQL
connection = mysql.connector.connect(
host='localhost',
user='root',
password='1909',
database='testdb'
)
cursor = connection.cursor()
# SQL Insert query (now including HostelID)
insert_query = """
INSERT INTO Hostel (HostelID, HostelName, Location, Rating,
RoomsAvailable, PricePerNight)
VALUES (%s, %s, %s, %s, %s, %s)
"""
# Input number of records
num_records = int(input("Enter the number of hostel records to insert: "))
records = []
# Collect data for each record
for i in range(num_records):
print(f"\nEnter details for hostel {i + 1}:")
hostel_id = int(input("Hostel ID (or leave blank to auto-generate): ") or 0)
# 0 for auto-generate
hostel_name = input("Hostel Name: ")
location = input("Location: ")
rating = float(input("Rating (0 to 5 scale): "))
rooms_available = int(input("Rooms Available: "))
price_per_night = float(input("Price per Night: "))
# Add the record to the list
records.append((hostel_id, hostel_name, location, rating,
rooms_available, price_per_night))
# Insert data into the table
cursor.executemany(insert_query, records)
connection.commit()
print(f"{cursor.rowcount} record(s) inserted successfully into the 'Hostel'
table.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
# Run the function
if __name__ == "__main__":
insert_hostel_records()
Output:
Write a Program to display all
records and implement name based
search
Input:
import mysql.connector
def display_all_records():
"""Fetch and display all records from the Hostel table."""
try:
# Connect to MySQL
connection = mysql.connector.connect(
host='localhost',
user='root',
password='1909',
database='testdb'
)
cursor = connection.cursor()
# Query to fetch all records
cursor.execute("SELECT * FROM Hostel")
records = cursor.fetchall()
# Display all records
if records:
print("\nAll Hostel Records:")
for record in records:
print(f"Hostel ID: {record[0]}, Hostel Name: {record[1]}, Location:
{record[2]}, "
f"Rating: {record[3]}, Rooms Available: {record[4]}, Price per
Night: {record[5]}")
else:
print("No records found.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
def search_hostel_by_name():
"""Search for a hostel by its name."""
try:
# Connect to MySQL
connection = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='testdb'
)
cursor = connection.cursor()
# User input for name-based search
search_name = input("Enter hostel name to search: ").strip()
# Query to search hostel by name (case-insensitive search)
search_query = "SELECT * FROM Hostel WHERE HostelName LIKE %s"
cursor.execute(search_query, ('%' + search_name + '%',))
records = cursor.fetchall()
# Display search results
if records:
print("\nSearch Results:")
for record in records:
print(f"Hostel ID: {record[0]}, Hostel Name: {record[1]}, Location:
{record[2]}, "
f"Rating: {record[3]}, Rooms Available: {record[4]}, Price per
Night: {record[5]}")
else:
print(f"No hostels found with name '{search_name}'.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
# Main function to run the program
def main():
while True:
print("\n1. Display All Hostel Records")
print("2. Search Hostel by Name")
print("3. Exit")
# User choice
choice = input("Enter your choice (1/2/3): ").strip()
if choice == '1':
display_all_records()
elif choice == '2':
search_hostel_by_name()
elif choice == '3':
print("Exiting program...")
break
else:
print("Invalid choice. Please try again.")
# Run the program
if __name__ == "__main__":
main()
Output:
Write a program to update hostel
rating to 5.0
Input:
import mysql.connector
def update_hostel_rating():
"""Update the rating of a hostel to 5.0 based on HostelID."""
try:
# Connect to MySQL
connection = mysql.connector.connect(
host='localhost',
user='root',
password='1909',
database='testdb'
)
cursor = connection.cursor()
# Input Hostel ID to update the rating
hostel_id = int(input("Enter Hostel ID to update the rating: "))
# SQL query to update the rating
update_query = "UPDATE Hostel SET Rating = 5.0 WHERE HostelID = %s"
# Execute the query with the user-provided Hostel ID
cursor.execute(update_query, (hostel_id,))
connection.commit()
# Check if any record was updated
if cursor.rowcount > 0:
print(f"Rating of Hostel ID {hostel_id} updated to 5.0 successfully.")
else:
print(f"No hostel found with ID {hostel_id}. No update performed.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
# Run the function
if __name__ == "__main__":
update_hostel_rating()
Output:
write a program to check
parenthesis in an expression are
balanced using stack
input:
def check_balanced_paranthesis():
expr=input("Enter Expression")
stack=[]
for char in expr:
if char=="(":
stack.append(char)
elif char==")":
if not stack:
print("Unbalanced Paranthesis")
return
stack.pop()
if stack:
print("Unbalanced Paranthesis")
else:
print("Balanced Paranthesis")
check_balanced_paranthesis()
Output:
THANK
YOU