Assignment-2
1. Implement a multi-threading program in Python where:
• One thread prints numbers from 1 to 10 with a delay of 1 second each.
• Another thread prints letters from ‘A’ to ‘J’ with a delay of 1 second each.
• Use thread synchronization to ensure both threads complete execution before exiting.
Source Code:
import threading
import time
def print_numbers():
for i in range(1, 11):
print(i)
[Link](1)
def print_letters():
for letter in range(ord('A'), ord('J') + 1):
print(chr(letter))
[Link](1)
if __name__ == "__main__":
try:
# Creating threads
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)
# Starting threads
[Link]()
[Link]()
# Ensuring both threads complete execution before exiting
[Link]()
[Link]()
print("Both threads have finished execution.")
except RuntimeError as e:
print(f"Error: {e}. Ensure system resources allow thread creation.")
Output:
2. Write a Python program that demonstrates exception handling by:
• Taking user input for division and handling ZeroDivisionError, ValueError, and a
user-defined exception called NegativeNumberError (raised when the input number is
negative).
• Using assert statements to ensure inputs are positive.
Source-code
class NegativeNumberError(Exception):
"""Custom exception for negative numbers."""
pass
def divide_numbers():
try:
# Taking user input
num1 = float(input("Enter numerator: "))
num2 = float(input("Enter denominator: "))
# Checking for negative numbers
assert num1 >= 0 and num2 >= 0, "Inputs must be positive."
# Raising custom exception if negative
if num1 < 0 or num2 < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
# Performing division
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
except NegativeNumberError as e:
print(f"Error: {e}")
except AssertionError as e:
print(f"AssertionError: {e}")
finally:
print("Execution completed.")
# Running the function
if __name__ == "__main__":
divide_numbers()
Output:
3. Write a Python program that:
• Creates a text file named student_data.txt and writes student records
(name, age, and marks) into it.
• Opens the file in read mode and displays its contents using read(),
readline(), and readlines().
• Implements error handling for file operations using try-except blocks to
handle file-related exceptions (e.g., FileNotFoundError, IOError).
• Renames the file to student_records.txt and then deletes it using
appropriate Python functions.
• Uses the pickle module to serialize and deserialize a dictionary containing
student data.
Source-Code:
import os
import pickle
# Function to create and write student data into a text file
def write_student_data():
try:
with open("student_data.txt", "w") as file:
[Link]("Name, Age, Marks\n")
[Link]("Alice, 20, 85\n")
[Link]("Bob, 22, 78\n")
[Link]("Charlie, 21, 90\n")
print("Student data successfully written to student_data.txt.")
except IOError as e:
print(f"Error writing to file: {e}")
# Function to read and display file contents using different read methods
def read_student_data():
try:
with open("student_data.txt", "r") as file:
print("\nReading entire file using read():")
print([Link]())
with open("student_data.txt", "r") as file:
print("\nReading line by line using readline():")
print([Link]().strip()) # Reads first line
print([Link]().strip()) # Reads second line
with open("student_data.txt", "r") as file:
print("\nReading all lines using readlines():")
for line in [Link]():
print([Link]())
except FileNotFoundError:
print("Error: student_data.txt not found.")
except IOError as e:
print(f"Error reading file: {e}")
# Function to rename and delete the file
def rename_and_delete_file():
try:
[Link]("student_data.txt", "student_records.txt")
print("\nFile renamed to student_records.txt.")
[Link]("student_records.txt")
print("File student_records.txt deleted successfully.")
except FileNotFoundError:
print("Error: File not found for renaming or deletion.")
except PermissionError:
print("Error: Permission denied while renaming or deleting the file.")
except IOError as e:
print(f"File operation error: {e}")
# Function to serialize and deserialize student data using pickle
def pickle_student_data():
student_dict = {
"Alice": {"Age": 20, "Marks": 85},
"Bob": {"Age": 22, "Marks": 78},
"Charlie": {"Age": 21, "Marks": 90}
}
# Serializing student data
try:
with open("student_data.pkl", "wb") as file:
[Link](student_dict, file)
print("\nStudent data serialized and saved as student_data.pkl.")
except IOError as e:
print(f"Error serializing data: {e}")
# Deserializing student data
try:
with open("student_data.pkl", "rb") as file:
loaded_data = [Link](file)
print("\nDeserialized Student Data:")
for name, info in loaded_data.items():
print(f"{name}: Age {info['Age']}, Marks {info['Marks']}")
except FileNotFoundError:
print("Error: student_data.pkl not found for deserialization.")
except [Link]:
print("Error: Corrupt data while deserializing.")
# Main function to execute all operations
if __name__ == "__main__":
write_student_data()
read_student_data()
rename_and_delete_file()
pickle_student_data()
OUTPUT:
[Link] a GUI-based student management system using Tkinter (or any GUI toolkit of
your choice) that performs CRUD operations on a database (SQLite/MySQL). The system
should include:
• A form with entry fields for Student ID, Name, Age, and Marks.
• Buttons for adding, updating, deleting, and displaying student records.
• A listbox or text area to display student records.
• A database connection where records are stored and retrieved from
SQLite/MySQL.
• Proper validation (e.g., preventing empty fields, ensuring marks are numeric).
SOURCE-CODE
import sqlite3
import tkinter as tk
from tkinter import messagebox
# Database Connection
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS students (
student_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
marks REAL NOT NULL
)
""")
[Link]()
# GUI Application
class StudentManagementApp:
def __init__(self, root):
[Link] = root
[Link]("Student Management System")
[Link]("500x500")
# Labels and Entry Fields
[Link](root, text="Student ID:").grid(row=0, column=0, padx=10, pady=5)
[Link](root, text="Name:").grid(row=1, column=0, padx=10, pady=5)
[Link](root, text="Age:").grid(row=2, column=0, padx=10, pady=5)
[Link](root, text="Marks:").grid(row=3, column=0, padx=10, pady=5)
self.student_id = [Link](root)
[Link] = [Link](root)
[Link] = [Link](root)
[Link] = [Link](root)
self.student_id.grid(row=0, column=1, padx=10, pady=5)
[Link](row=1, column=1, padx=10, pady=5)
[Link](row=2, column=1, padx=10, pady=5)
[Link](row=3, column=1, padx=10, pady=5)
# Buttons
[Link](root, text="Add", command=self.add_student).grid(row=4, column=0, pady=10)
[Link](root, text="Update", command=self.update_student).grid(row=4, column=1,
pady=10)
[Link](root, text="Delete", command=self.delete_student).grid(row=5, column=0,
pady=10)
[Link](root, text="Display", command=self.display_students).grid(row=5, column=1,
pady=10)
# Listbox for Displaying Data
[Link] = [Link](root, width=50)
[Link](row=6, column=0, columnspan=2, pady=10)
def validate_input(self):
"""Validates input fields before performing operations."""
if not self.student_id.get() or not [Link]() or not [Link]() or not [Link]():
[Link]("Error", "All fields must be filled!")
return False
if not [Link]().isdigit() or not [Link]().replace('.', '', 1).isdigit():
[Link]("Error", "Age and Marks must be numeric!")
return False
return True
def add_student(self):
"""Adds a new student record to the database."""
if not self.validate_input():
return
try:
[Link]("INSERT INTO students (student_id, name, age, marks) VALUES
(?, ?, ?, ?)",
(self.student_id.get(), [Link](), int([Link]()), float([Link]())))
[Link]()
[Link]("Success", "Student added successfully!")
self.clear_fields()
except [Link]:
[Link]("Error", "Student ID already exists!")
def update_student(self):
"""Updates an existing student record."""
if not self.validate_input():
return
[Link]("UPDATE students SET name=?, age=?, marks=? WHERE student_id=?",
([Link](), int([Link]()), float([Link]()), self.student_id.get()))
[Link]()
if [Link] > 0:
[Link]("Success", "Student updated successfully!")
else:
[Link]("Error", "Student ID not found!")
self.clear_fields()
def delete_student(self):
"""Deletes a student record based on Student ID."""
if not self.student_id.get():
[Link]("Error", "Enter Student ID to delete!")
return
[Link]("DELETE FROM students WHERE student_id=?", (self.student_id.get(),))
[Link]()
if [Link] > 0:
[Link]("Success", "Student deleted successfully!")
else:
[Link]("Error", "Student ID not found!")
self.clear_fields()
def display_students(self):
"""Displays all student records in the listbox."""
[Link](0, [Link])
[Link]("SELECT * FROM students")
records = [Link]()
for record in records:
[Link]([Link], record)
def clear_fields(self):
"""Clears all input fields."""
self.student_id.delete(0, [Link])
[Link](0, [Link])
[Link](0, [Link])
[Link](0, [Link])
# Running the Application
if __name__ == "__main__":
root = [Link]()
app = StudentManagementApp(root)
[Link]()
# Close DB connection when application exits
[Link]()
OUTPUT:
[Link] a Python program that:
• Uses NumPy and SciPy to solve a system of linear equations (e.g., Ax = B).
• Computes the determinant, inverse, and eigenvalues of a given matrix.
SOURCE-CODE:
import numpy as np
from [Link] import solve
def solve_linear_system():
"""Solves a system of linear equations Ax = B using SciPy."""
A = [Link]([[2, 1], [1, -1]]) # Coefficient matrix
B = [Link]([3, 0]) # Constant matrix
try:
X = solve(A, B) # Solving for x
print("Solution to Ax = B:", X)
except [Link] as e:
print("Error solving the system:", e)
def matrix_operations():
"""Computes determinant, inverse, and eigenvalues of a matrix."""
M = [Link]([[5, 2], [4, 1]]) # Example matrix
# Determinant
det = [Link](M)
print("\nDeterminant of M:", det)
# Inverse (if determinant is non-zero)
if det != 0:
inv = [Link](M)
print("Inverse of M:\n", inv)
else:
print("Matrix is singular; inverse does not exist.")
# Eigenvalues
eigenvalues, eigenvectors = [Link](M)
print("Eigenvalues of M:", eigenvalues)
print("Eigenvectors of M:\n", eigenvectors)
# Run the functions
solve_linear_system()
matrix_operations()
OUTPUT: