Exp No 5: GENERATE 5 RANDOM NUMBERS from 1 to 100
AIM : To write a Python program that generates random numbers using a while loop.
import random
count = 0
while count < 5:
num = random.randint(1, 100) # Generates a random number between 1 and 100
print("Random Number:", num)
count += 1
Ex: 6 FIBONACCI SERIES
AIM: To write a Python program that prints the Fibonacci series up to n terms using a for loop.
n = 10 # Number of terms in the Fibonacci series
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Ex: 7 TEXT FILE - READ OPERATION
AIM: To write a Python program that opens a text file in read mode and displays its content.
# Open the file in read mode
file = open("sample.txt", "r")
content = file.read() # Read the whole content
print(content) # Print the content
file.close() # Close the file
EX:8 TEXT FILE – COUNT THE NUMBER OF WORDS IN A FILE
AIM: To write a Python program that counts the total number of words present in a text file.
# Open the file in read mode.
file = open("sample.txt", "r")
content = file.read() # Read the entire content
words = content.split() # Split content into words
word_count = len(words) # Count the words
print("Total number of words in the file:", word_count)
file.close() # Close the file
Ex: 9 TEXT FILE – COUNT AND DISPLAY WORDS STARTING WITH ‘A” OR ‘a’
AIM: To write a Python program that reads a text file and counts and displays all words starting with the
letter 'A' or 'a'.
file = open("sample.txt", "r")
content = file.read() # Read the entire content (as string)
words = content.split() # Split into words
count = 0
print("Words starting with 'A' or 'a':")
for word in words:
if word.lower().startswith('a'):
print(word)
count += 1
print("\nTotal words starting with 'A' or 'a':", count)
file.close()
EX:10 BINARY FILE – READ & WRITE OPERATION
AIM:
To write a Python program to perform write and read operations on a binary file using the pickle
module.
PROGRAM:
import pickle
# Function to write data to a binary file
def write_data():
with open('student.dat', 'wb') as file:
while True:
roll = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
student = [roll, name, marks]
pickle.dump(student, file)
choice = input("Do you want to add more records? (y/n): ")
if choice.lower() != 'y':
break
print("Data written to binary file successfully.")
# Function to read data from a binary file
def read_data():
with open('student.dat', 'rb') as file:
print("\nReading data from binary file:")
while True:
try:
student = pickle.load(file)
print(f"Roll No: {student[0]}, Name: {student[1]}, Marks: {student[2]}")
except EOFError:
break
# Calling the functions
write_data()
read_data()
OUTPUT:
Enter Roll Number: 1
Enter Name: Deepa
Enter Marks: 90
Do you want to add more records? (y/n): y
Enter Roll Number: 2
Enter Name: John
Enter Marks: 85
Do you want to add more records? (y/n): n
Data written to binary file successfully.
Reading data from binary file:
Roll No: 1, Name: Deepa, Marks: 90.0
Roll No: 2, Name: John, Marks: 85.0
EX:11 BINARY FILE – SEARCH A RECORD
AIM:
To write a Python program to search a specific record in a binary file using the pickle module.
PROGRAM:
import pickle
def search_record(rollno):
found = False
with open('student.dat', 'rb') as file:
while True:
try:
student = pickle.load(file)
if student[0] == rollno:
print(f"Record Found:\nRoll No: {student[0]}, Name: {student[1]}, Marks: {student[2]}")
found = True
break
except EOFError:
break
if not found:
print("Record not found.")
# Function Call
roll = int(input("Enter roll number to search: "))
search_record(roll)
OUTPUT:
Enter roll number to search: 1
Record Found:
Roll No: 1, Name: Deepa, Marks: 90.0
Enter roll number to search: 3
Record not found.
EX 12: Binary File – Update a Record
AIM:
To write a simple Python program to update a record in a binary file using the pickle module.
PROGRAM :
import pickle
def update_record(rollno):
new_records = []
found = False
with open('student.dat', 'rb') as f:
while True:
try:
record = pickle.load(f)
if record[0] == rollno:
print("Old Record:", record)
name = input("Enter new name: ")
marks = float(input("Enter new marks: "))
record = [rollno, name, marks]
found = True
new_records.append(record)
except EOFError:
break
with open('student.dat', 'wb') as f:
for rec in new_records:
pickle.dump(rec, f)
if found:
print("Record updated successfully.")
else:
print("Record not found.")
# function call
r = int(input("Enter roll number to update: "))
update_record(r)
OUTPUT:
Enter roll number to update: 1
Old Record: [1, 'Deepa', 90.0]
Enter new name: Jo
Enter new marks: 78
Record updated successfully.
EX 13: CSV FILE READ AND WRITE
AIM:
To write a Python program to read from and write data to a CSV (Comma Separated Values) file using
CSV module.
PROGRAM:
import csv
# Function to write user input to CSV file
def write_csv_file():
n = int(input("Enter the number of students:
"))
with open('students.csv','w', newline='') as
file:
writer = csv.writer(file)
# Writing the header
writer.writerow(['Roll No', 'Name', 'Marks'])
OUTPUT:
# Taking user input and writing data
for i in range(n): Enter the number of students: 2
print(f"\nEnter details for student {i+1}:")
roll = input("Enter Roll Number: ") Enter details for student 1:
name = input("Enter Name: ") Enter Roll Number: 1001
marks = input("Enter Marks: ") Enter Name: John
writer.writerow([roll, name, marks]) Enter Marks: 90
print("Data successfully written.") Enter details for student 2:
Enter Roll Number: 1002
# Function to read data from CSV file Enter Name: Jo
def read_csv_file(): Enter Marks: 99
print("Reading data") Data successfully written
with open('students.csv','r') as file:
reader = csv.reader(file) Reading data
for row in reader:
print(row) ['Roll No', 'Name', 'Marks']
['1001', 'John', '90']
# Main Program ['1002', 'Jo', '99']
write_csv_file()
read_csv_file()
EX 14: IMPLEMENTATION OF STACK
AIM:
To write a menu-driven Python program to implement a stack using list with operations: push, pop,
update, and display.
PROGRAM:
# Stack to store book records
stack = []
# Function to push a book into the stack
def push():
bookname = input("Enter Book Name: ")
bookprice = input("Enter Book Price: ")
stack.append([bookname, bookprice])
print("Book added to the stack!\n")
# Function to pop a book from the stack
def pop():
if stack:
book = stack.pop()
print("Popped Book:", book, "\n")
else:
print("Stack is empty! No book to pop.\n")
# Function to display the top book in the stack
def peek():
if stack:
print("Top Book:", stack[-1], "\n")
else:
print("Stack is empty! No book to display.\n")
# Function to display all books in the stack
def display():
if stack:
print("Books in Stack:")
for book in reversed(stack): # Display from top to bottom
print(book)
print()
else:
print("Stack is empty! No books to display.\n")
# Main menu
while True:
print("Menu:")
print("1. Push (Add Book)")
print("2. Pop (Remove Book)")
print("3. Peek (Top Book)")
print("4. Display (Show All Books)")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
push()
elif choice == "2":
pop()
elif choice == "3":
peek()
elif choice == "4":
display()
elif choice == "5":
print("Exiting the program.")
break
else:
print("Invalid choice! Please try again.\n")
OUTPUT:
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 1
Enter Book Name: Malgudi days
Enter Book Price: 200
Book added to the stack!
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 1
Enter Book Name: The Alchemist
Enter Book Price: 250
Book added to the stack!
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 4
Books in Stack:
['The Alchemist', '250']
['Malgudi days', '200']
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 3
Top Book: ['The Alchemist', '250']
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 2
Popped Book: ['The Alchemist', '250']
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 5
Exiting the program
EX 15: IMPLEMENTATION OF STACK - DICTIONARY
AIM:
To implement a stack in Python where each element is a dictionary (e.g., storing book details), with
menu-driven options to push, pop, update, and display elements.
PROGRAM:
# Stack to store book records
stack = []
# Function to push a book into the stack
def push():
bookname = input("Enter Book Name: ")
bookprice = input("Enter Book Price: ")
stack.append({bookname:bookprice})
print("Book added to the stack!\n")
# Function to pop a book from the stack
def pop():
if stack:
book = stack.pop()
print("Popped Book:", book, "\n")
else:
print("Stack is empty! No book to pop.\n")
# Function to display the top book in the stack
def peek():
if stack:
print("Top Book:", stack[-1], "\n")
else:
print("Stack is empty! No book to display.\n")
# Function to display all books in the stack
def display():
if stack:
print("Books in Stack:")
for book in reversed(stack): # Display from top to bottom
print(book)
print()
else:
print("Stack is empty! No books to display.\n")
# Main menu
while True:
print("Menu:")
print("1. Push (Add Book)")
print("2. Pop (Remove Book)")
print("3. Peek (Top Book)")
print("4. Display (Show All Books)")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
push()
elif choice == "2":
pop()
elif choice == "3":
peek()
elif choice == "4":
display()
elif choice == "5":
print("Exiting the program.")
break
else:
print("Invalid choice! Please try again.\n")
OUTPUT:
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 1
Enter Book Name: Life of pi
Enter Book Price: 490
Book added to the stack!
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 1
Enter Book Name: The Alchemist
Enter Book Price: 250
Book added to the stack!
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 4
Books in Stack:
{'The Alchemist': '250'}
{'Life of pi': '490'}
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 3
Top Book: {'The Alchemist': '250'}
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 2
Popped Book: {'The Alchemist': '250'}
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 4
Books in Stack:
{'Life of pi': '490'}
Menu:
1. Push (Add Book)
2. Pop (Remove Book)
3. Peek (Top Book)
4. Display (Show All Books)
5. Exit
Enter your choice: 5
Exiting the program
EX 16: Binary File – Dictionary
AIM:
To write a menu-driven Python program to perform read, write, update, and delete operations on a
binary file storing dictionary records using the pickle module.
PROGRAM:
import pickle
filename = "data.dat"
# Function to add a new record
def write_record():
record = {}
record['Roll'] = input("Enter Roll Number: ")
record['Name'] = input("Enter Name: ")
record['Marks'] = input("Enter Marks: ")
with open(filename, 'ab') as file:
pickle.dump(record, file)
print("Record added successfully.")
# Function to display all records
def read_records():
with open(filename, 'rb') as file:
found = False
while True:
try:
record = pickle.load(file)
print(record)
found = True
except EOFError:
break
if found == False:
print("No records found")
# Function to update a record
def update_record():
found = False
temp = []
roll_to_update = input("Enter Roll Number to update: ")
with open(filename, 'rb') as file:
while True:
try:
record = pickle.load(file)
if record['Roll'] == roll_to_update:
print("Current Record:", record)
record['Name'] = input("Enter new Name: ")
record['Marks'] = input("Enter new Marks: ")
found = True
temp.append(record)
except EOFError:
break
with open(filename, 'wb') as file:
for record in temp:
pickle.dump(record, file)
if found:
print("Record updated successfully.")
else:
print("Record not found.")
# Function to delete a record
def delete_record():
found = False
temp = []
roll_to_delete = input("Enter Roll Number to delete: ")
with open(filename, 'rb') as file:
while True:
try:
record = pickle.load(file)
if record['Roll'] != roll_to_delete:
temp.append(record)
else:
found = True
except EOFError:
break
with open(filename, 'wb') as file:
for record in temp:
pickle.dump(record, file)
if found:
print("Record deleted successfully.")
else:
print("Record not found.")
# Menu-driven interface
while True:
print("\nBINARY FILE OPERATIONS (DICTIONARY RECORDS)")
print("1. Write (Add Record)")
print("2. Read (Display All Records)")
print("3. Update Record")
print("4. Delete Record")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
write_record()
elif choice == '2':
read_records()
elif choice == '3':
update_record()
elif choice == '4':
delete_record()
elif choice == '5':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
OUTPUT:
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 1
Enter Roll Number: 1
Enter Name: Andrew
Enter Marks: 90
Record added successfully.
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 1
Enter Roll Number: 2
Enter Name: Joy
Enter Marks: 99
Record added successfully.
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 2
{'Roll': '1', 'Name': 'Andrew', 'Marks': '90'}
{'Roll': '2', 'Name': 'Joy', 'Marks': '99'}
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 3
Enter Roll Number to update: 2
Current Record: {'Roll': '2', 'Name': 'Joy', 'Marks': '99'}
Enter new Name: jo
Enter new Marks: 100
Record updated successfully.
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 2
{'Roll': '1', 'Name': 'Andrew', 'Marks': '90'}
{'Roll': '2', 'Name': 'jo', 'Marks': '100'}
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 4
Enter Roll Number to delete: 1
Record deleted successfully.
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 2
{'Roll': '2', 'Name': 'jo', 'Marks': '100'}
BINARY FILE OPERATIONS (DICTIONARY RECORDS)
1. Write (Add Record)
2. Read (Display All Records)
3. Update Record
4. Delete Record
5. Exit
Enter your choice (1-5): 5
Exiting program
EX 17: MYSQL - Queries
Aim:
To perform basic database and table operations in MySQL, including creating, selecting, and dropping
databases; creating, altering, describing, and deleting tables; and applying constraints like primary key,
not null, unique, and check.
MYSQL Queries:
1. To create a new database named school:
CREATE DATABASE school;
2. To select and use the school database:
USE school;
3. To show all the databases present in the My server:
SHOW DATABASES;
4. To show all the tables in the currently selected database:
SHOW TABLES;
5. To create a table named students with the following structure:
id (INT, Not Null)
name (VARCHAR(50), Not Null)
age (INT, should be greater than 0)
CREATE TABLE students (
id INT NOT NULL,
name VARCHAR(50) NOT NULL,
age INT CHECK (age > 0),
);
6. To describe the structure of the students table:
DESCRIBE students;
7. To add a new column email (VARCHAR) to the students table:
ALTER TABLE students ADD email VARCHAR (100) unique;
8. To add a primary key on the id column in the students table:
ALTER TABLE students ADD PRIMARY KEY (id);
9. To drop the students table completely:
DROP TABLE students;
10. To drop the school database permanently:
DROP DATABASE school;
EX 18: MYSQL - DML Queries
Aim:
To perform Data Manipulation Language (DML) operations such as inserting, updating, deleting,
and retrieving records in a MySQL table named students.
DML Queries:
1. To Insert a new student record:
INSERT INTO students (id, name, age, email) VALUES (1, 'Ravi Kumar', 18,
'[email protected]');
2. To Insert another student record:
INSERT INTO students (id, name, age, email) VALUES (2, 'Anjali Sharma', 19,
'[email protected]');
3. To Insert a record without email:
INSERT INTO students (id, name, age) VALUES (3, 'Aman Verma', 20);
4. To Update age of student with ID 2:
UPDATE students SET age = 20 WHERE id = 2;
5. To Update email of student named 'Aman Verma':
UPDATE students SET email = '[email protected]' WHERE name = 'Aman Verma';
6. To Delete the student whose ID is 1:
DELETE FROM students WHERE id = 1;
7. To Select all student records:
SELECT * FROM students;
8. To Select name and email of all students:
SELECT name, email FROM students;
9. To Select students whose age is greater than 18:
SELECT * FROM students WHERE age > 18;
10. To Select students whose name starts with 'A':
SELECT * FROM students WHERE name LIKE 'A%';
EX 19: MYSQL - Queries
Aim:
To write and execute MySQL queries using SELECT statements, mathematical, relational and logical
operators, aliasing, DISTINCT, WHERE, IN, BETWEEN, ORDER BY, handling NULL values using IS NULL
and IS NOT NULL, pattern matching with LIKE, and performing data manipulation using UPDATE and
DELETE commands from the table student.
Table: student
id name age email
1 Ravi Kumar 18
[email protected] Anjali
2 Sharma 19
[email protected] 3 Aman Verma 20
[email protected] 4 Pooja Iyer 18
[email protected] 5 Nikhil Mehra 21 (NULL)
MYSQL Queries:
1. Display all records from the students table:
SELECT * FROM students;
2. Display id, name, and age increased by 1 as Next_Age
SELECT id, name, age + 1 AS Next_Age FROM students;
3. Display students whose age is greater than or equal to 19 :
SELECT * FROM students WHERE age >= 19;
4. Display students whose age is between 18 and 20 (inclusive):
SELECT * FROM students WHERE age BETWEEN 18 AND 20;
5. Display students whose name starts with 'A' or ends with 'r':
SELECT * FROM students WHERE name LIKE 'A%' OR name LIKE '%r';
6. Display unique ages from the students table using the DISTINCT clause:
SELECT DISTINCT age FROM students;
7. Display students whose age is either 18 or 21 using the IN clause:
SELECT * FROM students WHERE age IN (18, 21);
8. Display students in descending order of their age:
SELECT * FROM students ORDER BY age DESC;
9. Display students who have not provided their email address (IS NULL):
SELECT * FROM students WHERE email IS NULL;
10. Update the email address of the student with ID 5:
UPDATE students SET email = '
[email protected]' WHERE id = 5;
11. Delete the record of the student whose name is 'Ravi Kumar':
DELETE FROM students WHERE name = 'Ravi Kumar';
Exp No: 20 MYSQL Queries
Aim:
To perform aggregate operations using MySQL functions like MAX, MIN, AVG, SUM, and COUNT on the
employee table, and apply GROUP BY and HAVING clauses to summarize and filter grouped data
department-wise from the given table.
Table: Employee
emp_id name ag salary department
101 Ravi Kumar e 50000 HR
30
102 Anjali Mehra 28 55000 IT
103 Nikhil Rana 35 60000 Finance
104 Meera Singh 32 50000 IT
105 Karan Patel 29 40000 HR
106 Priya Iyer 31 75000 IT
107 Arjun Das 26 45000 Marketing
108 Neha Sharma 34 55000 Finance
MYSQL Queries:
1. Find the maximum salary among all employees:
SELECT MAX(salary) AS Highest_Salary FROM employee;
2. Find the minimum salary among all employees:
SELECT MIN(salary) AS Lowest_Salary FROM employee;
3. Find the average salary of all employees:
SELECT AVG(salary) AS Average_Salary FROM employee;
4. Find the total salary paid to all employees:
SELECT SUM(salary) AS Total_Salary FROM employee;
5. Count the total number of employees in the company:
SELECT COUNT(*) AS Total_Employees FROM employee;
6. Display the number of employees in each department:
SELECT department, COUNT(*) AS Employee_Count FROM employee GROUP BY department;
7. Display the average salary in each department:
SELECT department, AVG(salary) AS Average_Salary FROM employee GROUP BY department;
8. Display departments having more than 3 employees:
SELECT department, COUNT(*) AS Employee_Count FROM employee GROUP BY department
HAVING COUNT(*) > 3;
9. Display departments where the total salary is more than 1,00,000:
SELECT department, SUM(salary) AS Total_Department_Salary FROM employee GROUP BY
department HAVING SUM(salary) > 100000;
10. Display department-wise maximum salary:
SELECT department, MAX(salary) AS Max_Salary FROM employee GROUP BY department;
Exp No: 21 MYSQL - JOINS
Aim:
To perform and understand different types of joins in MySQL including Cartesian product, equi-join, and
natural join using two related tables: employee and department.
Table : employee
emp_id emp_name dept_id
1 Ravi Kumar 101
2 Anjali Mehra 102
3 Karan Patel 101
4 Meera Singh 103
5 Arjun Das 104
Table : department
dept_id dept_name
101 HR
102 IT
103 Finance
105 Marketing
MYSQL Queries:
1. Display the Cartesian product of employee and department tables (i.e., all
combinations of rows).
SELECT * FROM employee, department;
2. Display all combinations of employee names and department names using cross join.
SELECT e.emp_name, d.dept_name
FROM employee e
CROSS JOIN department d;
3. Display employee names along with their department names using equi-join.
SELECT e.emp_name, d.dept_name
FROM employee e, department d
WHERE e.dept_id = d.dept_id;
4. List employee IDs and department names where the employee and department are
matched by department ID.
SELECT e.emp_id, d.dept_name
FROM employee e
JOIN department d
ON e.dept_id = d.dept_id;
5. Display all employee details along with their matching department details using
natural join.
SELECT * FROM employee NATURAL JOIN department;
6. Display employee names and department names using natural join.
SELECT emp_name, dept_name FROM employee NATURAL JOIN department;