Practical 01
Write a program to display Fibonacci series up to “N” numbers using User Define Function
Input:
Output:
Practical 02
Write a menu driven python program to find the factorial and sum of list of numbers using
function. Using User Define Function
Practical 03
Write a python program to implement the mathematical function to find:
a. Square of a number
b. To find Log of a number (log10)
c. To find the square root of number Using User Define Function
Practical 04
Write a python program to generate random numbers between 1 to 6 to simulate the dice. Using
User Define Function
Practical 05
Write a program to check whether the string is Palindrome or not without using Slicing method.
Using User Define Function
Practical 06
Write a python program to read a text file “[Link]” and display the number of vowels,
consonant, lower case, upper case, special characters in a file. Using User Define Function
def analyze_text(story):
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
try:
with open("[Link]", 'r') as file:
text = [Link]()
vowel_count = 0
consonant_count = 0
lower_count = 0
upper_count = 0
special_count = 0
for char in text:
if [Link]():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
if [Link]():
lower_count += 1
else:
upper_count += 1
else:
special_count += 1
return {'vowels': vowel_count, 'consonants': consonant_count,
'lower_case': lower_count,
'upper_case': upper_count, 'special_characters': special_count}
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return None
# Get the filename from the user (optional)
filename = input("Enter the filename (default: [Link]): ") or "[Link]"
# Analyze the text and display the results
results = analyze_text(filename)
if results:
print("Analysis Results:")
print("Vowels:", results['vowels'])
print("Consonants:", results['consonants'])
print("Lower Case:", results['lower_case'])
print("Upper Case:", results['upper_case'])
print("Special Characters:", results['special_characters'])
Practical 07
Python program to read the text file line by line and display each word separated by #. Using
User Define Function
Practical 10
Write a program in python to write some records in a binary file “[Link]” and search
the record. The student record contains admission number, name, class, roll no and
percentage. Searching is done for a specific admission number. Using User Define
Function
Input Code
import pickle
class Student:
def __init__(self, admission_no, name, class_, roll_no, percentage):
self.admission_no = admission_no
[Link] = name
self.class_ = class_
self.roll_no = roll_no
[Link] = percentage
def write_records():
"""Writes student records to a binary file."""
with open("[Link]", "wb") as file:
while True:
admission_no = int(input("Enter Admission No. (0 to stop): "))
if admission_no == 0:
break
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
student = Student(admission_no, name, class_, roll_no, percentage)
[Link](student, file)
def search_record():
"""Searches for a student record by admission number."""
admission_no = int(input("Enter Admission No. to search: "))
try:
with open("[Link]", "rb") as file:
while True:
try:
student = [Link](file)
if student.admission_no == admission_no:
print(f"Admission No.: {student.admission_no}")
print(f"Name: {[Link]}")
print(f"Class: {student.class_}")
print(f"Roll No.: {student.roll_no}")
print(f"Percentage: {[Link]}")
return
except EOFError:
break
print("Record not found.")
except FileNotFoundError:
print("File '[Link]' not found.")
if __name__ == "__main__":
while True:
print("\n1. Write Records")
print("2. Search Record")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
write_records()
elif choice == 2:
search_record()
elif choice == 3:
break
else:
print("Invalid choice.")
Practical 11
Write a program in python to update the record in a binary file “[Link]” and search
the record. The student record contains admission number, name, class, roll no and
percentage. Updating is done in percentage on a specific admission number. Using User
Define Function
import pickle
class Student:
def __init__(self, admission_no, name, class_, roll_no, percentage):
self.admission_no = admission_no
[Link] = name
self.class_ = class_
self.roll_no = roll_no
[Link] = percentage
def write_records():
"""Writes student records to a binary file."""
with open("[Link]", "wb") as file:
while True:
admission_no = int(input("Enter Admission No. (0 to stop): "))
if admission_no == 0:
break
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
student = Student(admission_no, name, class_, roll_no, percentage)
[Link](student, file)
def search_record():
"""Searches for a student record by admission number."""
admission_no = int(input("Enter Admission No. to search: "))
try:
with open("[Link]", "rb") as file:
while True:
try:
student = [Link](file)
if student.admission_no == admission_no:
print(f"Admission No.: {student.admission_no}")
print(f"Name: {[Link]}")
print(f"Class: {student.class_}")
print(f"Roll No.: {student.roll_no}")
print(f"Percentage: {[Link]}")
return
except EOFError:
break
print("Record not found.")
except FileNotFoundError:
print("File '[Link]' not found.")
def update_record():
"""Updates the percentage of a student record."""
admission_no = int(input("Enter Admission No. to update: "))
new_percentage = float(input("Enter New Percentage: "))
try:
with open("[Link]", "rb+") as file:
found = False
while True:
try:
pos = [Link]() # Store current position in the file
student = [Link](file)
if student.admission_no == admission_no:
[Link] = new_percentage
# Move file pointer back to the beginning of the record
[Link](pos, 0)
[Link](student, file)
found = True
break
except EOFError:
break
if found:
print("Record updated successfully.")
else:
print("Record not found.")
except FileNotFoundError:
print("File '[Link]' not found.")
if __name__ == "__main__":
while True:
print("\n1. Write Records")
print("2. Search Record")
print("3. Update Record")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
write_records()
elif choice == 2:
search_record()
elif choice == 3:
update_record()
elif choice == 4:
break
else:
print("Invalid choice.")
Practical 12
Write a program in python to append the record in a binary file “[Link]” The student
record contains admission number, name, class, roll no and percentage. Using User
Define Function
import pickle
class Student:
def __init__(self, admission_no, name, class_, roll_no, percentage):
self.admission_no = admission_no
[Link] = name
self.class_ = class_
self.roll_no = roll_no
[Link] = percentage
def append_record():
"""Appends a new student record to the binary file."""
try:
with open("[Link]", "ab") as file: # Open in binary append mode
admission_no = int(input("Enter Admission No.: "))
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
student = Student(admission_no, name, class_, roll_no, percentage)
[Link](student, file)
print("Record appended successfully.")
except FileNotFoundError:
print("File '[Link]' not found. Creating a new file.")
write_records() # If file doesn't exist, call write_records() to create it
def write_records():
"""Writes student records to a binary file."""
with open("[Link]", "wb") as file:
while True:
admission_no = int(input("Enter Admission No. (0 to stop): "))
if admission_no == 0:
break
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
student = Student(admission_no, name, class_, roll_no, percentage)
[Link](student, file)
if __name__ == "__main__":
append_record()
Practical 13
Write a program to insert and delete the record of a student in a binary file “[Link]”
The student record contains admission number, name, class, roll no and percentage.
Using User Define Function
import pickle
class Student:
def __init__(self, admission_no, name, class_, roll_no, percentage):
self.admission_no = admission_no
[Link] = name
self.class_ = class_
self.roll_no = roll_no
[Link] = percentage
def write_records():
"""Writes student records to a binary file."""
with open("[Link]", "wb") as file:
while True:
admission_no = int(input("Enter Admission No. (0 to stop): "))
if admission_no == 0:
break
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
student = Student(admission_no, name, class_, roll_no, percentage)
[Link](student, file)
def insert_record():
"""Inserts a new student record at the beginning of the file."""
try:
with open("[Link]", "rb+") as file: # Open in read-write mode
temp_file = []
admission_no = int(input("Enter Admission No.: "))
name = input("Enter Name: ")
class_ = input("Enter Class: ")
roll_no = int(input("Enter Roll No.: "))
percentage = float(input("Enter Percentage: "))
new_student = Student(admission_no, name, class_, roll_no, percentage)
temp_file.append(new_student)
while True:
try:
student = [Link](file)
temp_file.append(student)
except EOFError:
break
[Link](0) # Move the file pointer to the beginning
for student in temp_file:
[Link](student, file)
print("Record inserted successfully.")
except FileNotFoundError:
print("File '[Link]' not found.")
def delete_record():
"""Deletes a student record by admission number."""
admission_no = int(input("Enter Admission No. to delete: "))
try:
with open("[Link]", "rb+") as file:
temp_file = []
found = False
while True:
try:
student = [Link](file)
if student.admission_no != admission_no:
temp_file.append(student)
else:
found = True
except EOFError:
break
if found:
[Link](0) # Move the file pointer to the beginning
[Link]() # Truncate the file to remove existing data
for student in temp_file:
[Link](student, file)
print("Record deleted successfully.")
else:
print("Record not found.")
except FileNotFoundError:
print("File '[Link]' not found.")
if __name__ == "__main__":
while True:
print("\n1. Write Records")
print("2. Insert Record")
print("3. Delete Record")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
write_records()
elif choice == 2:
insert_record()
elif choice == 3:
delete_record()
elif choice == 4:
break
else:
print("Invalid choice.")
Practical 14
Write a program to create a CSV file to store some records of an employee contain
employee number, name, salary and display them. Using User Define Function.
Practical 15
Write a program to create a CSV file to store some records of an employee contain
employee number, name, salary and search for a specific record. Also display message
“Found and not Found”. Using User Define Function
Practical 16
Write a python program to implement stack using list data structure. Using
User Define Function
class Stack:
def __init__(self):
"""
Initializes an empty stack using a list.
"""
[Link] = []
def is_empty(self):
"""
Checks if the stack is empty.
Returns:
bool: True if the stack is empty, False otherwise.
"""
return len([Link]) == 0
def push(self, item):
"""
Adds an item to the top of the stack.
Args:
item: The item to be added to the stack.
"""
[Link](item)
def pop(self):
"""
Removes and returns the item from the top of the stack.
Returns:
The item removed from the top of the stack, or None if the stack is empty.
"""
if self.is_empty():
return None
return [Link]()
def peek(self):
"""
Returns the item at the top of the stack without removing it.
Returns:
The item at the top of the stack, or None if the stack is empty.
"""
if self.is_empty():
return None
return [Link][-1]
# Example usage:
if __name__ == "__main__":
stack = Stack()
[Link](1)
[Link](2)
[Link](3)
print("Popped element:", [Link]()) # Output: 3
print("Top element:", [Link]()) # Output: 2
print("Stack is empty:", stack.is_empty()) # Output: False
while not stack.is_empty():
print("Popped element:", [Link]())
Practical 17
Write a python program to implement connectivity with My SQL to insert record in
employee table and display the records. Using User Define Function.
Input Code:
import [Link]
from [Link] import Error
def create_connection():
"""Establishes connection to the MySQL database."""
try:
connection = [Link](
host='localhost',
user='root',
password='12345',
database='company_db' # Ensure this database exists
)
return connection
except Error as e:
print(f"Error: {e}")
return None
def insert_employee(id, name, department, salary):
"""Inserts a new record into the employee table."""
conn = create_connection()
if conn:
cursor = [Link]()
query = "INSERT INTO employee (emp_id, name, dept, salary) VALUES (%s, %s,
%s, %s)"
data = (id, name, department, salary)
try:
[Link](query, data)
[Link]()
print("Record inserted successfully!")
except Error as e:
print(f"Failed to insert record: {e}")
finally:
[Link]()
[Link]()
def display_records():
"""Fetches and displays all records from the employee table."""
conn = create_connection()
if conn:
cursor = [Link]()
try:
[Link]("SELECT * FROM employee")
records = [Link]()
print("\n--- Employee Records ---")
for row in records:
print(f"ID: {row[0]} | Name: {row[1]} | Dept: {row[2]} | Salary: {row[3]}")
except Error as e:
print(f"Error reading data: {e}")
finally:
[Link]()
[Link]()
# --- Main Execution Block ---
if __name__ == "__main__":
# Example: Inserting a record
insert_employee(101, 'Alice Smith', 'Engineering', 75000)
insert_employee(102, 'Bob Johnson', 'Marketing', 62000)
# Displaying all records
display_records()
Practical 18
Write a python program to integrate MY SQL with python to search an employee using
EMPID and display the record if present in already exiting table EMP, if not display
appropriate message. Using User Define Function
Input Code:
import [Link]
from [Link] import Error
def search_employee(emp_id):
"""
Searches for an employee in the EMP table using EMPID.
"""
try:
# 1. Establish connection
conn = [Link](
host='localhost',
user='root', # Replace with your MySQL username
password='12345', # Replace with your MySQL password
database='company_db'
)
if conn.is_connected():
cursor = [Link]()
# 2. Define the search query
query = "SELECT * FROM EMP WHERE EMPID = %s"
# 3. Execute query with the emp_id parameter
[Link](query, (emp_id,))
# 4. Fetch one record
record = [Link]()
if record:
print(f"\n Record Found for ID: {emp_id}")
print("-" * 30)
print(f"Name: {record[1]}")
print(f"Department: {record[2]}")
print(f"Salary: {record[3]}")
print("-" * 30)
else:
print(f"\n Error: No record found for EMPID {emp_id}.")
except Error as e:
print(f"Error connecting to MySQL: {e}")
finally:
# 5. Clean up connection
if 'cursor' in locals():
[Link]()
if 'conn' in locals() and conn.is_connected():
[Link]()
# --- Main Program ---
if __name__ == "__main__":
search_id = input("Enter the Employee ID to search: ")
search_employee(search_id)
Practical 20
Write a SQL command to create the table EMP with code, name, department,
designation, experience, gender, salary, city with appropriate data types. Use constraints
to make code as primary key salary between 20000 to 50000 and default designation as
“Worker”.
Show output.
Practical 21
Write a SQL command to insert some records in the above table of EMP.
Show output.
Practical 22
Write a SQL command to display the records of employee belonging to sales department
and getting salary between 25000 to 35000.
Show output.
Practical 23
Write a SQL command to arrange the records of male employee in ascending order of
salary of employees having experience more than 20 years.
Show output.
Practical 24
Write a SQL command to display the number of employees in each department in the
above table EMP.
Show output.
Practical 25
Write a SQL command to display the minimum and the maximum salary of each
department.
Show output.
Practical 26
Write a SQL command to add a new column “mobile number” in the above table of EMP
Show output.
Practical 28
Write a SQL command to delete the record of employees with experience less than 5
years.
Show output.
Practical 29
Write a SQL command to create another table “Employee duplicate” from the table EMP
containing all fields and all records of table EMP.
Show output.
Practical 30
Write a command to remove the table ‘Employee duplicate’ from database.
Show output.